package com.epalmpay.service.posapi;

import com.alibaba.fastjson.JSON;
import com.epalmpay.commom.LoginController;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.*;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.service.activity.IActivityCouponService;
import com.epalmpay.service.activity.ICouponUserService;
import com.epalmpay.service.activity.IRedPackageUserService;
import com.epalmpay.service.app.IAppNoticeService;
import com.epalmpay.service.groupaccount.IGroupAccountService;
import com.epalmpay.service.jobservice.IProfitStatisService;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.thread.AfterRebackMoneyThread;
import com.epalmpay.service.thread.AfterTransUploadThread;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.WxService;
import com.epalmpay.status.Rescode;
import com.epalmpay.util.*;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.payplat.Base64Utils;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.SysUtils;
import com.epalmpay.util.payplat.UtilFun;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

/**
 * Created by lifayi on 2017/6/16.
 */
@Service("posApiService")
public class PosApiService {
	@Autowired  @Lazy
	private ITemplateMailSendService templateMailSendService;
    @Autowired
    private DevicePosMapper devicePosMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private CouponUserMapper couponUserMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private TradeOfflineMapper tradeOfflineMapper;
    @Autowired
    private OrderServiceGoodMapper orderServiceGoodMapper;
    @Autowired
    private ActivityUnroutineRuleMapper activityUnroutineRuleMapper;
    @Autowired
    private ActivityUnroutineShopPlusMapper activityUnroutineShopPlusMapper;
    @Autowired
    private ActivityBaseMapper activityBaseMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private ShopGroupRelationMapper shopGroupRelationMapper;
    @Autowired
    private MemberICCardInfoMapper memberICCardInfoMapper;
    @Autowired
    private MemberGradeMapper memberGradeMapper;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private OrderServiceGoodDetailMapper orderServiceGoodDetailMapper;
    @Autowired
    private ShopUserMapper shopUserMapper;
    @Autowired
    private ActivityUnroutineMapper activityUnroutineMapper;
    @Autowired
    private CrcodeMapper crcodeMapper;
    @Autowired
    private RedpackageUserMapper redpackageUserMapper;
    @Autowired
    private BonusVerifyLogMapper bonusVerifyLogMapper;
    @Autowired
    private BonusSendLogMapper bonusSendLogMapper;
    @Resource
    private MallGoodMapper mallGoodMapper;
    @Resource
    private BonusVerifyShopMapper bonusVerifyShopMapper;
    @Resource
    private BonusVerifyRuleMapper bonusVerifyRuleMapper;
    @Resource
    private UserbaseMapper userbaseMapper;

    @Resource
    private OrderGoodMapper orderGoodMapper;
    
    @Resource
    private DeviceMapper deviceMapper;

    @Autowired
    private IRedPackageUserService iRedPackageUserService;
    @Autowired
    private ICouponUserService iCouponUserService;
    @Autowired
    private IProfitStatisService profitStatisService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IActivityCouponService activityCouponService;
    @Autowired
    protected WxService wxService;
    @Autowired
    protected IWxBaseService wxBaseService;


    @Resource
    private PosApiServiceTransactional posApiServiceTransactional;
    @Resource
    private PosApiServiceCacheable posApiServiceCacheable;
    @Resource
    private IGroupAccountService groupAccountService;

    private ExecutorService exec;

    @Resource
    private IAppNoticeService appNoticeService;
    
    @Resource
	private IWalletService walletService;

    @PostConstruct
	public void initialize() {
		exec = Executors.newSingleThreadExecutor();
	}


    /**
     * 异步执行
     */
    public void saveSynNewBenefitCalc( final Long sid, final Integer realAmount,final Long groupId,final Member member,
                                       final String payOrderNo, final Long tradeOfflineId) {
    	exec.submit((new Runnable() {
  			@Override
  			public void run() {
  				try {
  					newBenefitCalc(sid, realAmount, groupId, member, payOrderNo, tradeOfflineId);
  				}catch (Exception e){
                      logger.error(e);
                      e.printStackTrace();
  				}
  			}
  		}));
  		
	}

    private Logger logger = Logger.getLogger(this.getClass());


    public PayResult synUpdatePayConsumption(final String virtualCard, final String payGroupCode,final Long userId,
                                             final Integer actualTranAmt, final String orgOrderNum,final String payPwd,
                                             final String merchantId,final String orgOrderNum1) throws ExecutionException, InterruptedException, ApplicationException {
        logger.info ("=====================异步开始==============");

        Callable<PayResult> callable = new Callable<PayResult>() {
            @Override
            public PayResult call() throws TaskException, ApplicationException {
                return walletService.updatePayConsumption(virtualCard, payGroupCode, userId, actualTranAmt, orgOrderNum, payPwd, merchantId, orgOrderNum1);

            }
        };
        FutureTask<PayResult> future = new FutureTask<PayResult>(callable)  ;
        try {
            new Thread(future).start();

            System.out.println(future.get());
            logger.info ("=====================结果=="+future.get());
            return future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
//            String errorCode = ((TaskException) e.getCause()).getErrorCode();
//            String message = ((TaskException) e.getCause()).getMessage();
//            System.out.println(errorCode);
//            logger.info("================="+errorCode);
//            logger.info("================="+message);
////            throw new ApplicationException(errorCode);
//            future.cancel(true);
            e.printStackTrace();



        }
        return future.get();

    }




    //1.签到
    public Map<String,Object> posSignIn(Map<String, Object> params) {
        String posNumber = (String) params.get("pos_number");
        if(Tools.isEmpty(posNumber)) {
            return null;
        }

        Map<String, Object> posSignInfo = devicePosMapper.getPosSignInInfo(posNumber);
        if(posSignInfo != null) {
            posSignInfo.put("responseCode", 1);
            //目前先返回为空
            Long shopId = (Long) posSignInfo.get("sid");
            List<Map<String, String>> operator_list = userbaseMapper.listShopCashier(shopId);

            posSignInfo.put("operatList", null);
            posSignInfo.put("operator_list", operator_list);
        } else {
            posSignInfo = new HashMap<>();
            posSignInfo.put("responseCode", -1);
            posSignInfo.put("responseMsg", "设备不存在");
        }

        return posSignInfo;
    }

    //2.获取会员权益
    public Map<String,Object>   benefits(Map<String, Object> params) {
        Integer sidInt = (Integer) params.get("sid");
        String mobile = (String) params.get("mobile");
        Integer tradeMoney = (Integer) params.get("tradeMoney");
        if(sidInt == null || Tools.isEmpty(mobile) || tradeMoney == null) {
            return null;
        }

        Long sid = (long) sidInt;
        Date now = new Date();

        Map<String, Object> userCouponInfo = new HashMap<>();
        userCouponInfo.put("isMember", true);

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(sid);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }
        Long groupId = (Long) shopInfo.get("groupId");

        Member member = memberMapper.getMemberByCardNoOrPhone(sid, mobile); //查询用户信息
        if(member != null) {                   //已经存在则查询相关权益
            userCouponInfo.put("memberName", member.getName());
            userCouponInfo.put("memberCardNo", member.getCardNo());
            userCouponInfo.put("mobile", member.getPhone());
            userCouponInfo.put("icCardNo",member.getIccardNo());
            List<Map<String, Object>> userCoupons = couponUserMapper.listUserCouponsInfo(member.getId(), ActivityEnum.CouponUseStatus.Received.getType(),
                    tradeMoney, ActivityEnum.ActivityPlatformType.OffLine.getType(), null);
            if (userCoupons == null || userCoupons.size() == 0) {
                userCouponInfo.put("couponNum", 0);
                userCouponInfo.put("coupons", new ArrayList<Map>());
            } else {
                Iterator<Map<String, Object>> couponIterator = userCoupons.iterator();
                while (couponIterator.hasNext()) {
                    Map<String, Object> coupon = couponIterator.next();

                    //优惠券是否在有效期
                    if ((Integer) coupon.get("validTimeType") == ActivityEnum.ValidTimeType.FixedTime.getType()) {
                        if (now.compareTo((Date) coupon.get("validStartTime")) < 0 || now.compareTo((Date) coupon.get("validEndTime")) > 0) {
                            couponIterator.remove();
                            continue;
                        }
                    } else if ((Integer) coupon.get("validTimeType") == ActivityEnum.ValidTimeType.AfterGet.getType()) {
                        Integer days = (Integer) coupon.get("days");
                        Date validUseEnd = DateUtil.getDateNext((Date) coupon.get("getTime"), days);
                        if (now.compareTo(validUseEnd) > 0) {
                            couponIterator.remove();
                            continue;
                        }
                    } else { //其他有效日期类型无效
                        couponIterator.remove();
                        continue;
                    }

                    //优惠券在门店是否可用
                    String shopIdsStr = (String) coupon.get("shopIds");
                    String[] shopIds;
                    if (shopIdsStr == null) {
                        couponIterator.remove();
                        continue;
                    } else if (shopIdsStr.equals("-1")) {    //所有门店可用
                        continue;
                    } else {
                        shopIds = shopIdsStr.split(",");
                    }

                    boolean contains = false;
                    for (int j = 0; j < shopIds.length; j++) {
                        if (Long.parseLong(shopIds[j]) == sid) {
                            contains = true;
                            break;
                        }
                    }
                    if (!contains) {
                        couponIterator.remove();
                    }
                    coupon.remove("shopIds");   //移除门店信息
                }
                userCouponInfo.put("couponNum", userCoupons.size());
                userCouponInfo.put("coupons", userCoupons);
            }

            //积分
            Map<String, Integer> userCanVerifyBonus = posApiServiceTransactional.userCanVerifyBonus(sid, groupId, member, now, tradeMoney);

            userCouponInfo.put("point", member.getBonusAmount());
            userCouponInfo.put("pointUseMax", userCanVerifyBonus.get("pointUseMax"));
            userCouponInfo.put("frequency_min", userCanVerifyBonus.get("frequency_min"));
            userCouponInfo.put("pointChangeRate", userCanVerifyBonus.get("verifyRate"));
            userCouponInfo.put("cantVerifyReason", userCanVerifyBonus.get("cantVerifyReason"));
//            if (userCoupons == null || userCoupons.size() == 0) {
//                userCouponInfo.put("freePassword", false);
//            } else {
                userCouponInfo.put("freePassword", true);
//            }
        } else {
            if(Tools.checkMobileNumber(mobile)) {
                //创建用户信息
                Group group = groupMapper.selectByPrimaryKey(groupId);

           //     MemberGrade memberGrade = memberGradeMapper.selectMemberGradeByGroupIdAndGradeName(groupId, BizEnum.MemberGradeDefault.unattention.getName());
                
                List<MemberGrade> memberGradeList=memberGradeMapper.selectGroupList(groupId);

                Userbase userbase = new Userbase();
                userbase.setStatus(BizEnum.UserStatus.Normal.getType());
                userbase.setUserType(CommonEnum.UserType.User.getType());
                userbase.setGmtCreate(now);
                userbase.setGroupId(groupId);
                userbase.setUsername(mobile);

                Member member1 = new Member();
                member1.setGroupId(groupId);
                member1.setPhone(mobile);
                member1.setName(mobile);
                member1.setFromType(BizEnum.MemberDevelopeFrom.ShopDevelope.getType());
                member1.setFromMode(BizEnum.MemberDevelopeMode.PosConsume.getType());
                member1.setFromId(sid);
                member1.setFromName((String) shopInfo.get("shopName"));
                member1.setStatus(BizEnum.MemberStatus.unattention.getType());
                member1.setGmtCreate(now);
                member1.setWalletGmtCreate(now);
                member1.setWalletStatus(1);
                member1.setWxsubStaus(0);
                if(memberGradeList.size()>1) {
                    member1.setGradeId(memberGradeList.get(1).getId());
                }
                  String password="888888";
               // String  password=mobile.substring(mobile.length()-6);
                member1.setTradePassword(AES.AESEncode(Const.AceKey, password));

                //会员卡号生成
                String virtualCardNO = "" + group.getPayGroupCode() + sid + (new Date().getTime()+"").substring(0, 10);
                member1.setVirtualCard(virtualCardNO);
                member1.setCardNo("VIP" + DateUtil.getMonth()+Tools.getRandomNum(6));
                logger.info("===========虚拟卡号=="+virtualCardNO);
                logger.info("===========userId=="+userbase.getId());
                logger.info("===========payGroupCode()=="+group.getPayGroupCode());

                try {
                  posApiServiceTransactional.saveCreateMember(userbase, member1, group.getPayGroupCode());
                } catch (Exception e) {
                    e.printStackTrace();
                    userCouponInfo.put("responseCode", -1);
                    userCouponInfo.put("responseMsg", "服务器处理错误");
                    return userCouponInfo;
                }

                userCouponInfo.put("mobile", mobile);
                userCouponInfo.put("memberCardNo", member1.getCardNo());
                userCouponInfo.put("couponNum", 0);
                userCouponInfo.put("coupons", new ArrayList<Map>());

                //积分
                userCouponInfo.put("frequency_min", 0);
                userCouponInfo.put("pointUseMax", 0);
                userCouponInfo.put("point", 0);
                userCouponInfo.put("pointChangeRate", 0);

                userCouponInfo.put("freePassword", true);
            } else {
                userCouponInfo.put("responseCode", -1);
                userCouponInfo.put("responseMsg", "账户不存在");
                return userCouponInfo;
            }
        }
        userCouponInfo.put("responseCode", 1);
        return userCouponInfo;
    }

    

 

    //3.交易金额计算
    public Map<String,Object> tranMoney(Map<String, Object> params) {

        Integer sidStr;
        Integer tradeMoney;
        Integer point;
        if(!Tools.isEmpty(params.get("sid")+"")){
             sidStr = Integer.valueOf(params.get("sid")+"");
        }else{
             sidStr = 0;
        }
        if(!Tools.isEmpty(params.get("tradeMoney")+"")){
            tradeMoney = Integer.valueOf(params.get("tradeMoney")+"");
        }else{
            tradeMoney = 0;
        }
        if(!Tools.isEmpty(params.get("point")+"")){
            point = Integer.valueOf(params.get("point")+"");
        }else{
            point = 0;
        }

        System.out.print(":::::::::::"+tradeMoney);


        if(sidStr == null) {
            return null;
        }
        Long sid = (long) sidStr;
        String cardNo = (String) params.get("memberCardNo");
        String password = (String) params.get("password");


        String couponCodeStr = (String) params.get("couponSn");
        String memberName = (String) params.get("memberName");
        String clientOrderNo = (String) params.get("clientOrderNo");

        if((couponCodeStr != null || point != 0) && password == null) {
            return null;
        }

        if(Tools.isEmpty(cardNo) || tradeMoney == null || point == null || Tools.isEmpty(clientOrderNo)) {
            return null;
        }

        Map<String, Object> tranMoneyInfo = new HashMap<>();
        tranMoneyInfo.put("memberCardNo", cardNo);      //会员卡号
        tranMoneyInfo.put("tradeMoney", tradeMoney);    //交易金额
        if(couponCodeStr != null) {
            tranMoneyInfo.put("couponSns", couponCodeStr);  //消费优惠券
        }

        //会员确认
        if(!Tools.isEmpty(password)) {
            String result = new String(Base64Utils.decode(password));
        	password = AES.AESEncode(Const.AceKey, result);
        }

        Member member = memberMapper.checkMember(sid, cardNo, password);
        if(member != null) {
            tranMoneyInfo.put("memberName", member.getName());      //会员名称
        } else {
            tranMoneyInfo.put("responseCode", -1);
            tranMoneyInfo.put("responseMsg", "支付密码错误");
            return tranMoneyInfo;
        }

        Date date = new Date();
        //积分抵用金额计算
        int pointCoverAmount = 0;
        if(point > 0) {
            Map<String, Integer> userCanVerifyBonus = posApiServiceTransactional.userCanVerifyBonus(sid, member.getGroupId(), member, date, tradeMoney);

            if(userCanVerifyBonus.get("pointUseMax") != 0 &&
                    point >= userCanVerifyBonus.get("frequency_min") && point <= userCanVerifyBonus.get("pointUseMax")) {
                pointCoverAmount = new BigDecimal(point).divide(new BigDecimal(userCanVerifyBonus.get("verifyRate")),2,BigDecimal.ROUND_FLOOR).multiply(new BigDecimal(100)).intValue();
            } else {
                tranMoneyInfo.put("responseCode", -1);
                tranMoneyInfo.put("responseMsg", "积分不可核销，请重试");
                return tranMoneyInfo;
            }
        }


        //优惠券计算和锁定
        Map coupon;
        Integer couponCoverMoney = 0;
        if(!Tools.isEmpty(couponCodeStr)) {
            String[] couponCodes = couponCodeStr.split(",");
            String couponCode = couponCodes[0];     //这一版优惠券不能叠加使用
            coupon = posApiServiceTransactional.saveCalcAndLockCoupon(couponCode, member.getId(), tradeMoney, sid, clientOrderNo);

            if(coupon != null) {
                int value = (Integer) coupon.get("money");

                System.out.print(":::::::::::value="+value);

                if((Integer)coupon.get("couponType") == ActivityEnum.CouponType.DiscountCoupon.getType()) {
                    couponCoverMoney = tradeMoney - new BigDecimal(tradeMoney).multiply(new BigDecimal(value)).divide(new BigDecimal(1000), 2, BigDecimal.ROUND_FLOOR).intValue();
                } else {
                    couponCoverMoney = value;
                }
                System.out.print(":::::::::::couponCoverMoney="+couponCoverMoney);
                tranMoneyInfo.put("couponName", coupon.get("name"));            //优惠券名称
                tranMoneyInfo.put("couponCoverMoney", couponCoverMoney);     //优惠券抵消金额
                tranMoneyInfo.put("couponNum", 1);                              //消费优惠券数量//这一版优惠券不能叠加
            } else {
                tranMoneyInfo.put("responseCode", -1);
                tranMoneyInfo.put("responseMsg", "优惠券不可用");
                return tranMoneyInfo;
            }
        }

        int realMoney = tradeMoney - couponCoverMoney - pointCoverAmount;
        realMoney = realMoney >= 0 ? realMoney : 0;

        logger.debug("---------------"+point+"----------------");
        logger.debug("---------------"+pointCoverAmount+"----------------");
        logger.debug("---------------添加交易流水----------------");

        //添加交易流水
        TradeOffline tradeOffline = new TradeOffline();
        tradeOffline.setOrderId(clientOrderNo);
        tradeOffline.setGroupId(member.getGroupId());
        tradeOffline.setPayerId(member.getId());
        tradeOffline.setPayerName(member.getName());
        tradeOffline.setPayerType(((byte) CommonEnum.UserType.User.getType()));
        tradeOffline.setReceiverId(sid.toString());
        tradeOffline.setGmtCreate(date);
        tradeOffline.setGmtModified(date);
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        tradeOffline.setRealAmount(realMoney);
        tradeOffline.setOrderAmount(tradeMoney);

        //积分抵扣金额大于订单金额
        if(couponCoverMoney>tradeMoney){
            tradeOffline.setDiscountAmount(tradeMoney);
        }else{
            tradeOffline.setDiscountAmount(couponCoverMoney);
        }
        tradeOffline.setBonusAmount(point);
        tradeOffline.setBonusValue(pointCoverAmount);

        //锁定积分
        BonusVerifyLog bonusVerifyLog = new BonusVerifyLog();
        bonusVerifyLog.setGmtCreate(date);
        bonusVerifyLog.setGmtModified(date);
        bonusVerifyLog.setMemberId(member.getId());
        bonusVerifyLog.setVerifyType(ActivityEnum.BonusVerityType.Consume.getType());
        bonusVerifyLog.setAdjustAmount(point);
        bonusVerifyLog.setAdjustValue(pointCoverAmount);
        bonusVerifyLog.setAdjustStatus(ActivityEnum.BonusVerityStatus.Locked.getType());
        bonusVerifyLog.setShopId(sid);
        bonusVerifyLog.setMemo("创建订单锁定积分");
        bonusVerifyLog.setGroupId(member.getGroupId());

        //积分结算到门店开始
        if(sid !=null){

            //结算积分给门店 start
            Integer bonusamount = tradeOffline.getBonusAmount();
            Long groupId = tradeOffline.getGroupId();
            if(bonusamount != 0) {
                float settlerate = 0;
                //根据shopid获取积分结算规则
                BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(sid);
                if (bonusVerifyRule != null) {//如果有门店自定义的
                    settlerate = bonusVerifyRule.getSettleRate();
                } else {//如果商圈给门店设置的
                    bonusVerifyRule = bonusVerifyRuleMapper.selectBonusSettleRate(sid, groupId);
                    if (bonusVerifyRule != null) {
                        settlerate = bonusVerifyRule.getSettleRate();
                    } else {
                        bonusVerifyRule = bonusVerifyRuleMapper.selectBonusVeriftyRuleByGroupId(groupId);
                        if (bonusVerifyRule != null) {
                            settlerate = bonusVerifyRule.getSettleRate();
                        }
                    }
                }

                //计算积分
                if (settlerate != 0) {
                    int bonus = (int) (bonusamount * settlerate / 100);

                    logger.info("+++++++结算到门店的积分+++++++"+bonus);
                    //添加积分结算记录
                    bonusVerifyLog.setSettingAmount(bonus);

                }
            }
            //结算积分给门店 end

        }


        try {
            posApiServiceTransactional.saveCreateOrder(member, tradeOffline, bonusVerifyLog);
        } catch (ApplicationException e) {
            e.printStackTrace();
            tranMoneyInfo.put("responseCode", -1);
            tranMoneyInfo.put("responseMsg", "创建订单失败");
            return tranMoneyInfo;
        }

        tranMoneyInfo.put("tradeOrderNo", cardNo);
        tranMoneyInfo.put("pointCoverMoney", pointCoverAmount);
        tranMoneyInfo.put("realMoney", realMoney);      //实收金额
        tranMoneyInfo.put("responseCode", 1);
        return tranMoneyInfo;


    }

    //4.上传交易流水
    public Map<String,Object> tranUploadPos(Map<String, Object> params) throws Exception {
      
        Long sid = SysUtils.Object2Long(params.get("sid"));
        Long t = SysUtils.Object2Long(params.get("t"));
        if(sid == null || t == null) {
            return null;
        }
        String orderNo = (String) params.get("clientOrderNo");  //订单号
        String termSerial = (String) params.get("serialNum");   //终端设备序列号
        Integer payType = (Integer) params.get("payType");      //支付类型
        String cardNo = (String) params.get("cardNo");          //会员卡号
        String activateCode = (String) params.get("activateCode");  //终端号 终端序列号（钱包）
        String merchantNo = (String) params.get("merchantNo");  //商户号 大商户号（钱包）
        String transNo = (String) params.get("transNo");        //交易流水号
        String couponSns = (String) params.get("couponSns");    //优惠券
        String authCode = (String) params.get("authCode");      //交易机构订单号
        String payCardNo = (String) params.get("payCardNo"); //支付卡号

        Integer payAmount;                               //支付金额

        Integer cash = (Integer) params.get("cash");
        if(cash == null || cash == 0) {
            payAmount = (Integer) params.get("bankAmount");
        } else {
            payAmount = cash;
        }
//        Integer couponCoverAmount = (Integer) params.get("couponCoverAmount");
//        if(couponCoverAmount == null) {
//            couponCoverAmount = 0;
//        }
//        Integer pointCoverAmount = (Integer) params.get("pointCoverAmount");
//        if(pointCoverAmount == null) {
//            pointCoverAmount = 0;
//        }

        if(payType == null || Tools.isEmpty(orderNo) || Tools.isEmpty(termSerial)) {
            return null;
        }

        Map<String, Object> result1 = devicePosMapper.getScanOrganizationByPosTerminalSn(termSerial);
        if(result1 == null) {
            return null;
        }

        Byte subType = 0;

        switch (payType) {
            case 6:
                subType = (byte)BizEnum.PaymentScene.POS.getType();
                break;
            case 1:
            case 3:
            case 4:
            case 5:
            case 13:
                subType = (byte)BizEnum.PaymentScene.Scan.getType();
                break;
        }

        Date date = new Date();
        //返回数据
        Map<String, Object> newBenefitInfo = new HashMap<>();
        Map shop = shopMapper.getShopById(sid);

        Device device = deviceMapper.selectByserialNum(termSerial);
        if(device==null||!sid.equals(device.getShopId())){
        	 newBenefitInfo.put("responseCode", -1);
             newBenefitInfo.put("responseMsg", "POS不存在");
             return newBenefitInfo; 
        }
        Long groupId=device.getGroupId();
        
        //交易流水创建或修改
        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(orderNo);



        
        Member member = null;
        if(!Tools.isEmpty(cardNo)) {
            //会员交易
            member = memberMapper.getMemberByCardNoOrPhone(sid, cardNo); //查询用户信息
            if(member != null) {
                groupId = member.getGroupId();
            } else {
                newBenefitInfo.put("responseCode", -1);
                newBenefitInfo.put("responseMsg", "请求非法");
                return newBenefitInfo;
            }
        } 
        
      //判断使用的优惠券是否是异业优惠券
    	
    	if(StringUtils.isNotBlank(couponSns)){
    		 try {
				member =finishProcessOtherSns(couponSns, member);
			} catch (Exception e) {
				e.printStackTrace();
				 newBenefitInfo.put("responseCode", -1);
	                newBenefitInfo.put("responseMsg", "优惠券码不存在");
	                return newBenefitInfo;
			}
    	}
        if(member==null){
            //非会员交易
        		 logger.debug(">>>>>>非会员交易处理");
                 if(tradeOffline == null) {
                     tradeOffline = new TradeOffline();
                 } else {
                     //如果POS机端重新上传交易流水，并且本交易已经处理成功
                     if(tradeOffline.getTransactionStatus()==(byte)BizEnum.TransactionStatus.Success.getType()) {
                         newBenefitInfo = getBenefitInfo(tradeOffline, transNo, newBenefitInfo);
                         newBenefitInfo.put("responseCode", 1);
                         return newBenefitInfo;
                     }
                 }

                 tradeOffline.setGroupId(groupId);
                 tradeOffline.setRealAmount(payAmount);
                 tradeOffline.setOrderAmount(payAmount);
                 tradeOffline.setDiscountAmount(0);
                 tradeOffline.setOrderId(orderNo);
                 tradeOffline.setPayType((byte)(int)payType);
                 tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
                 tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                 tradeOffline.setTermSerial(termSerial);
                 tradeOffline.setMerchantNo(merchantNo);
                 tradeOffline.setTerminalNo(activateCode);
                 tradeOffline.setTransNo(transNo);
                 tradeOffline.setTransOrderNo(authCode);
                 tradeOffline.setScanOrganization((byte)(int) result1.get("scanOrganization"));
                 tradeOffline.setIsWallet(false);
                 tradeOffline.setGmtCreate(date);
                 tradeOffline.setGmtModified(date);
                 tradeOffline.setReceiverName((String) shop.get("merchant_name"));
                 tradeOffline.setReceiverId(sid.toString());
                 tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
                 tradeOffline.setSubType(subType);
                 tradeOffline.setPayAccount(payCardNo);
                 int i=0;
                 if(tradeOffline.getId()!=null&&tradeOffline.getId()>0){
                     logger.debug("---------------更新----------------");
                	  i = tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
                 }else{
                     logger.debug("---------------新增----------------");
                	  i = tradeOfflineMapper.insertSelective(tradeOffline);
                 }

                //推送交易信息给APP
                Userbase userbase = shopMapper.getUserNameByShopId(Long.parseLong(shop.get("id").toString()));
            logger.debug("---------------getGroupId----------------"+userbase.getGroupId() == null ? "0" : userbase.getGroupId());

                //发送推送信息
                Notice notice = new Notice();
                try {
                    notice.setNoticetype(0);
                    notice.setSender(userbase.getGroupId());
                    notice.setReceiver(userbase.getUsername());
                    notice.setNoticetitle("您有一笔新的收入");
                    notice.setNoticetarget("ACCOUNT");
                    notice.setNoticebody(BizEnum.PaymentType.fromType(payType).getName()+"收入"+Double.parseDouble(payAmount+"")/100+"元");
                    notice.setGroupid(userbase.getGroupId());
                    notice.setNoticestatus(1);
                    notice.setIsplay(1);
                    notice.setType(4);
                    notice.setTvalue(tradeOffline.getId() + "#" + 0);
                    appNoticeService.sendNoticeToUsers(notice);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                 if(StringUtils.isNotBlank(couponSns)){
                	 try {
                         posApiServiceTransactional.saveVerifyCouponAndUpdateTrade(tradeOffline, couponSns, sid);
                     } catch (ApplicationException e) {
                         e.printStackTrace();
                         newBenefitInfo.put("responseCode", -1);
                         newBenefitInfo.put("responseMsg", "服务器处理错误");
                         return newBenefitInfo;
                     }
                 }
                 if(i == 1) {
                     newBenefitInfo = newBenefitCalc(sid, payAmount, groupId, null, orderNo, tradeOffline.getId());
                     newBenefitInfo.put("responseCode", 1);
                     newBenefitInfo.put("responseMsg", "处理成功");
                 } else {
                     newBenefitInfo.put("responseCode", -1);
                     newBenefitInfo.put("responseMsg", "服务器处理错误");
                 }
                 return newBenefitInfo;
        	}
        

        //会员交易继续处理(不使用优惠)
        if(tradeOffline == null) {
            tradeOffline = new TradeOffline();
            tradeOffline.setReceiverId(sid.toString());
            tradeOffline.setGroupId(member.getGroupId());
            tradeOffline.setGmtCreate(date);
            tradeOffline.setGmtModified(date);
            tradeOffline.setOrderId(orderNo);
//            tradeOffline.setBonusAmount(0);
//            tradeOffline.setBonusValue(0);
//            tradeOffline.setDiscountAmount(0);
            tradeOffline.setOrderAmount(payAmount);
            tradeOffline.setRealAmount(payAmount);
        } else {
            //如果POS机端重新上传交易流水，并且本交易已经处理成功
            if(tradeOffline.getTransactionStatus()==(byte)BizEnum.TransactionStatus.Success.getType()) {
                newBenefitInfo = getBenefitInfo(tradeOffline, transNo, newBenefitInfo);
                newBenefitInfo.put("responseCode", 1);
                return newBenefitInfo;
            }
        }

        tradeOffline.setGroupId(member.getGroupId());
        tradeOffline.setPayType((byte)(int)payType);
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        tradeOffline.setTermSerial(termSerial);
        tradeOffline.setMerchantNo(merchantNo);
        tradeOffline.setTerminalNo(activateCode);
        tradeOffline.setTransNo(transNo);
        tradeOffline.setTransOrderNo(authCode);
        tradeOffline.setScanOrganization((byte)(int) result1.get("scanOrganization"));
        tradeOffline.setGmtModified(new Date());
        tradeOffline.setPayerId(member.getId());
        tradeOffline.setPayerName(member.getName());
        tradeOffline.setPayerType((byte)CommonEnum.UserType.User.getType());
        tradeOffline.setReceiverName((String) shop.get("merchant_name"));
        tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
        tradeOffline.setSubType(subType);
        tradeOffline.setPayAccount(payCardNo);

        if(payType == 13 || payType == 14) {
            tradeOffline.setIsWallet(true);
        } else {
            tradeOffline.setIsWallet(false);
        }

        try {
            posApiServiceTransactional.saveVerifyCouponAndUpdateTrade(tradeOffline, couponSns, sid);


            System.out.print("--------------"+"开始"+"---------------------");
            //首次交易满多多送 积分 优惠券 红包 返现
            int result = memberService.updateMemberFirstTradeSend(tradeOffline.getId(),tradeOffline.getPayerId(),tradeOffline.getGroupId(),tradeOffline.getRealAmount());

        } catch (ApplicationException e) {
            e.printStackTrace();
            newBenefitInfo.put("responseCode", -1);
            newBenefitInfo.put("responseMsg", "服务器处理错误");
            return newBenefitInfo;
        }

        try {
            memberService.insertMemberTradeDataAsyn(member.getId(),tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //新建线程进行分润计算和会员消费数据计算
        new Thread(new AfterTransUploadThread(tradeOffline.getId(), profitStatisService)).start();

        //推送交易信息给APP
        Userbase userbase = shopMapper.getUserNameByShopId(Long.parseLong(shop.get("id").toString()));
        //发送推送信息
        Notice notice = new Notice();
        try {
            notice.setNoticetype(0);
            notice.setSender(member.getGroupId());
            notice.setReceiver(userbase.getUsername());
            notice.setNoticetitle("您有一笔新的收入");
            notice.setNoticetarget("ACCOUNT");
            notice.setNoticebody(BizEnum.PaymentType.fromType(payType).getName()+"收入"+Double.parseDouble(payAmount+"")/100+"元");
            notice.setGroupid(member.getGroupId());
            notice.setNoticestatus(1);
            notice.setIsplay(1);
            notice.setType(4);
            notice.setTvalue(tradeOffline.getId() + "#" + tradeOffline.getPayerId());
            appNoticeService.sendNoticeToUsers(notice);
        } catch (Exception e) {
            e.printStackTrace();
        }

      /*  //结算积分给门店 start
        Integer bonusamount = tradeOffline.getBonusAmount();
        if(bonusamount != 0) {
            Long shopid = Long.parseLong(shop.get("id").toString());
            float settlerate = 0;
            //根据shopid获取积分结算规则
            BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(shopid);
            if (bonusVerifyRule != null) {//如果有门店自定义的
                settlerate = bonusVerifyRule.getSettleRate();
            } else {//如果商圈给门店设置的
                bonusVerifyRule = bonusVerifyRuleMapper.selectBonusSettleRate(shopid, groupId);
                if (bonusVerifyRule != null) {
                    settlerate = bonusVerifyRule.getSettleRate();
                } else {
                    bonusVerifyRule = bonusVerifyRuleMapper.selectBonusVeriftyRuleByGroupId(groupId);
                    if (bonusVerifyRule != null) {
                        settlerate = bonusVerifyRule.getSettleRate();
                    }
                }
            }

            //计算积分
            if (settlerate != 0) {
                int bonus = (int) (bonusamount * settlerate / 100);
                //积分结算给门店
                bonusVerifyShopMapper.insertShopVerifyBonus(groupId, shopid, bonus);

                //添加积分结算记录
                BonusVerifyLog record = new BonusVerifyLog();
                record.setGroupId(groupId);
                record.setMemberId(member.getId());
                record.setVerifyType(ActivityEnum.BonusVerityType.Consume.getType());
                record.setAdjustAmount(bonus);
                record.setShopId(shopid);
                record.setOrderId(tradeOffline.getId());
                record.setAdjustStatus(ActivityEnum.BonusVerityStatus.OutAccounted.getType());
                bonusVerifyLogMapper.insert(record);
            }
        }
        //结算积分给门店 end*/

        //会员门店关系
        memberShopRelation(member.getId(), sid, date, payAmount);

        //计算新的会员权益
        newBenefitInfo = newBenefitCalc(sid, payAmount, groupId, member, orderNo, tradeOffline.getId());
        newBenefitInfo.put("responseCode", 1);
        return newBenefitInfo;
    }

    /**
     * 处理异业联盟优惠券
     * @param couponSns
     * @return
     * @throws Exception 
     */
    private Member finishProcessOtherSns(String couponSns, Member member2) throws Exception {
		String[]couponSnArr=couponSns.split(",");
    	for(String couponSn:couponSnArr){
    		CouponUser couponUser=couponUserMapper.selectByCouponSn(couponSn);
    		Coupon coupon=couponMapper.selectByPrimaryKey(couponUser.getCouponId());
    		if(couponUser==null||coupon==null){
    			throw new Exception("优惠券码不存在");
    		}
    		if(couponUser.getMemberId()!=null&&coupon.getPurposeType().intValue()==ActivityEnum.PurposeType.otherCoupon.getType()){
    			//表示异业联盟优惠券，且没有注册会员 就用相同的信息注册会员
    			//创建用户信息
    			Long groupId =coupon.getGroupId();
    	        Group group = groupMapper.selectByPrimaryKey(groupId);
    	        
    	        Group otherGroup = groupMapper.selectByPrimaryKey(coupon.getReceiveGroupid());

    	//        MemberGrade memberGrade = memberGradeMapper.selectMemberGradeByGroupIdAndGradeName(groupId, BizEnum.MemberGradeDefault.unattention.getName());
    	        
    	        List<MemberGrade> memberGradeList=memberGradeMapper.selectGroupList(groupId);
    	      
    	        Member member=memberMapper.selectByPrimaryKey(couponUser.getMemberId());
    	        
    	        //查询当前大商户 这个用户是否已经是这个的会员
    	        Member member1 =  memberMapper.selectByPhone(member.getPhone(), groupId);
    	        if(member1!=null){
    	        	return member1;
    	        }
    	        Date now=new Date();
    	        Userbase userbase = new Userbase();
    	        userbase.setStatus(BizEnum.UserStatus.Normal.getType());
    	        userbase.setUserType(CommonEnum.UserType.User.getType());
    	        userbase.setGmtCreate(now);
    	        userbase.setGroupId(group.getId());
    	        userbase.setUsername(member.getPhone());

    	        member1 = new Member();
    	        member1.setGroupId(groupId);
    	        member1.setPhone(member.getPhone());
    	        member1.setName(member.getName());
    	        member1.setFromType(BizEnum.MemberDevelopeFrom.GroupDevelope.getType());
    	        member1.setFromMode(BizEnum.MemberDevelopeMode.ShareCoupon.getType());
    	        member1.setFromId(otherGroup.getId());
    	        member1.setFromName(otherGroup.getMerchantName());
    	        member1.setStatus(BizEnum.MemberStatus.unattention.getType());
    	        member1.setGmtCreate(now);
    	        member1.setWalletGmtCreate(now);
    	        member1.setWalletStatus(1);
    	        member1.setWxsubStaus(0);
//    	        if(memberGrade != null) {
//    	            member1.setGradeId(memberGrade.getId());
//    	        }
    	        if(memberGradeList.size()>1){
    	        	member1.setGradeId(memberGradeList.get(1).getId());
    	        }
    	          String password="888888";
    	       // String  password=mobile.substring(mobile.length()-6);
    	        member1.setTradePassword(AES.AESEncode(Const.AceKey, password));
    	        //会员卡号生成
    	        String virtualCardNO = "" + group.getPayGroupCode()  + (new Date().getTime()+"").substring(0, 10);
    	        member1.setVirtualCard(virtualCardNO);
    	        member1.setCardNo("VIP" + DateUtil.getMonth()+Tools.getRandomNum(6));
    	       
    	        try {
    	          posApiServiceTransactional.saveCreateMember(userbase, member1, group.getPayGroupCode());
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	        }
    	        couponUser.setRateMemberId(member1.getId());
    	        couponUserMapper.updateByPrimaryKeySelective(couponUser);
    	        return member1;
    		}else{
    		    return member2;
            }
    	}
    	  return null;
	}

	//会员消费权益计算
    public Map<String, Object> newBenefitCalc( Long sid, Integer payAmount, Long groupId, Member member, String orderNo, Long tradeOfflineId) {
        //获取大商户下未关注会员等级ID
        Long memberGradeId;
        if(member != null) {
            memberGradeId = member.getGradeId();
        } else {
        //    memberGradeId = memberGradeMapper.selectMemberGradeByGroupIdAndGradeName(groupId, BizEnum.MemberGradeDefault.unattention.getName()).getId();
	        	List<MemberGrade> memberGradeList=memberGradeMapper.selectGroupList(groupId);
	        	if(memberGradeList.size()>1){
	        		memberGradeId = memberGradeList.get(1).getId();
	        	}else{
	        		memberGradeId=1L;
	        	}
        	
        }

        Shop shop = shopMapper.selectByPrimaryKey(sid);

        //查询门店活动信息
        List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.getByShopIdAndTradeAmount(sid.toString(), payAmount, groupId,memberGradeId);
        logger.debug(">>>>>>活动规则：" + activityUnroutineRuleList);
        Group group= groupMapper.selectByPrimaryKey(groupId);
        String payGroupCode =group .getPayGroupCode();
        HashMap<String, Object> newBenefitInfo=new HashMap<String, Object>();

        logger.debug(">>>>>>动态活动送开始：" + activityUnroutineRuleList);

        int bonusValue = 0;
        for(int z = 0; z <activityUnroutineRuleList.size(); z++) {
            ActivityUnroutineRule activityUnroutineRule = activityUnroutineRuleList.get(z);

            Byte sendType = activityUnroutineRule.getSendType();

            if (sendType == ActivityEnum.ActivitySendType.Cash.getType() && member != null &&
                    member.getWalletStatus() != null && member.getWalletStatus()==1) {

                logger.debug(">>>>>>会员消费开始返利：" + activityUnroutineRuleList);

                Integer backAmt = activityUnroutineRule.getFaceValue();

                ActivityUnroutineShopPlus activityUnroutineShopPlus = activityUnroutineShopPlusMapper.selectByActivityIdAndShopId(activityUnroutineRule.getActivityId(), sid);
                if (activityUnroutineRule.getBackMoneyMode() == ActivityEnum.BackMoneyMode.FiexedAmount.getType()) {
                    if (activityUnroutineShopPlus != null) {
                        backAmt += activityUnroutineShopPlus.getAdditionalFaceValue();
                    }
                } else {
                    if (activityUnroutineShopPlus != null) {
                        backAmt = new BigDecimal(backAmt + activityUnroutineShopPlus.getAdditionalFaceValue()).divide(new BigDecimal(100),2,BigDecimal.ROUND_FLOOR).multiply(new BigDecimal(payAmount))
                        		.divide(new BigDecimal(100),2,BigDecimal.ROUND_FLOOR).intValue();
                    } else {
                        backAmt = new BigDecimal(backAmt).divide(new BigDecimal(100), 2, BigDecimal.ROUND_FLOOR).multiply(new BigDecimal(payAmount)).divide(new BigDecimal(100),2,BigDecimal.ROUND_FLOOR).intValue();
                    }
                }

                //余额增加操作
                Date date = new Date();
                String OrgOrderNum = UtilFun.createOrderNum();
                TradeOffline tradeOffline = new TradeOffline();
                tradeOffline.setGroupId(groupId);
                tradeOffline.setTransactionType((byte) BizEnum.TransactionType.ConsumptionBackCash.getType());
                tradeOffline.setOrderId(OrgOrderNum);            
                tradeOffline.setPayOrderid(OrgOrderNum);
                tradeOffline.setPayerId(member.getGroupId());
                tradeOffline.setPayerName(group.getMerchantName());
                tradeOffline.setPayerType((byte) CommonEnum.UserType.BusinessManager.getType());
                tradeOffline.setReceiverId(member.getId().toString());
                tradeOffline.setReceiverName(member.getName());
                tradeOffline.setReceiverType((byte) CommonEnum.UserType.User.getType());
                tradeOffline.setOrderAmount(backAmt);
                tradeOffline.setRealAmount(backAmt);
                tradeOffline.setDiscountAmount(0);
                tradeOffline.setSubType((byte)BizEnum.PaymentScene.POS.getType());
                tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
                tradeOffline.setGmtCreate(date);
                tradeOffline.setGmtModified(date);
                tradeOffline.setRelatedTradeOfflineId(tradeOfflineId);
                tradeOffline.setRelatedActivityId(activityUnroutineRule.getActivityId());
                tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                tradeOffline.setMemo("用户消费返现");
                tradeOffline.setIsWallet(true);


                tradeOfflineMapper.insertSelective(tradeOffline);

               
//                PayBalanceChange payBalanceChange = PayBalanceChange.initialize(payGroupCode, member.getVirtualCard(), backAmt.toString(), "0", OrgOrderNum, DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createRandomNum(10), "156");

                try {
//                    posApiServiceTransactional.saveRebackMoney(tradeOffline, payBalanceChange, tradeOfflineId);
                    
                	PayResult flag=walletService.updateUserLockedAmount(member.getVirtualCard(), payGroupCode, member.getUserId(), backAmt+"", "0", 0,OrgOrderNum);
                    if(flag!=null){
		            	throw new ApplicationException("支付平台余额增加失败");
		            }



                    
                    newBenefitInfo.put("backAmt", backAmt);
                    logger.debug(">>>>>>返现操作成功，返现金额：" + backAmt);

                    //异步操作扣除营销账户，扣除已使用预算，检查活动是否结束
                    new Thread(new AfterRebackMoneyThread(activityUnroutineRule.getActivityId(), backAmt, activityBaseMapper, groupAccountService,null, groupId)).start();
                } catch (ApplicationException e) {
                    System.out.println(e.getErrMsg());
                    newBenefitInfo.put("backAmt", 0);
                }
            //消费送优惠券
            } else if (sendType == ActivityEnum.ActivitySendType.Coupon.getType()) {
                logger.debug(">>>>>>会员消费准备反红包：" + activityUnroutineRuleList);
                String[] couponIdsStr = activityUnroutineRule.getCouponId().split(",");
                List<Long> couponIds = new ArrayList<>();
                if(member != null) {
                    for (int i = 0; i < couponIdsStr.length; i++) {
                        Long couponId = Long.parseLong(couponIdsStr[i]);
                        try {
                            int x = iCouponUserService.sendOneMemberCoupon(member.getId(), couponId, activityUnroutineRule.getActivityId(), ActivityEnum.RedPackageGetType.ConsumeSend.getType(), tradeOfflineId);
                            if(x == 1) {
                                couponIds.add(couponId);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    for(String couponId : couponIdsStr) {
                        couponIds.add(Long.parseLong(couponId));
                    }
                }

                if(couponIds.size() > 0) {
                    List<Map<String, Object>> couponsInfo = couponMapper.getCouponListById(couponIds);
                    List<Map<String, Object>> coupon = new ArrayList<>();
                    for (int i = 0; i < couponsInfo.size(); i++) {
                        Map<String, Object> coupon1 = new HashMap<>();
                        coupon1.put("coupon_id", couponsInfo.get(i).get("id"));
                        coupon1.put("coupon_name", couponsInfo.get(i).get("name"));
                        coupon1.put("coupon_money", couponsInfo.get(i).get("value"));
                        coupon1.put("coupon_type", couponsInfo.get(i).get("couponType"));
                        coupon.add(coupon1);
                    }
                    newBenefitInfo.put("coupon", coupon);
                    logger.debug(">>>>>>优惠券：" + coupon);
                }
            //消费送红包
            } else if(sendType == ActivityEnum.ActivitySendType.RedPackage.getType()) {

                logger.debug(">>>>>>会员消费准备返红包：" + activityUnroutineRuleList);
                Long redpackageId = activityUnroutineRule.getRedpackageId();
                if(member != null) {
                    try {
                        iRedPackageUserService.sendOneMemberRedPackage(member.getId(), redpackageId, activityUnroutineRule.getActivityId(), ActivityEnum.RedPackageGetType.ConsumeSend.getType(), tradeOfflineId);
                        //生成领取红包二维码
                        Integer lastSenseId = crcodeMapper.getPosRedPackageSenseId();
                        if(lastSenseId == null) {
                            lastSenseId = 2000000000;
                        }
                        wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupId));
                        WxMpQrCodeTicket ticket = this.wxService.getQrcodeService().qrCodeCreateTmpTicket(lastSenseId + 1, 2592000);
                        String weixinurl = this.wxService.getQrcodeService().qrCodePictureUrl(ticket.getTicket(),true);
                        Crcode crcode = new Crcode();
                        crcode.setGmtCreate(new Date());
                        //这里存储订单号为了重新打印时可以获取到红包二维码信息
                        crcode.setQrcode(orderNo);
                        crcode.setSceneid(lastSenseId + 1);
                        crcode.setQrcodePicurl(weixinurl);
                        crcode.setQrcodeName("POS红包");
                        crcode.setStatus(1);
                        crcode.setUserId(shop.getUserId());
                        crcode.setType(BizEnum.ScancrcodeType.posRedEnvelope.getType());
                        crcode.setScanTimes(0);
                        crcodeMapper.insert(crcode);
                        newBenefitInfo.put("coupon_url", weixinurl);
                        logger.debug(">>>>>>红包领取URL：" + weixinurl);
                    } catch (Exception a) {
                        a.printStackTrace();
                    }
                } else {
                    newBenefitInfo.put("redpackageId", redpackageId);
                }

            //消费送积分
            } else if (sendType == ActivityEnum.ActivitySendType.Bonus.getType() && member != null) {

                logger.debug(">>>>>>会员消费返积分：" + activityUnroutineRuleList);

                int backPoint = activityUnroutineRule.getFaceValue();

                ActivityUnroutineShopPlus activityUnroutineShopPlus = activityUnroutineShopPlusMapper.selectByActivityIdAndShopId(activityUnroutineRule.getActivityId(), sid);

                logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>11backPoint：" + backPoint);
                logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>payAmount：" + payAmount);

                if (activityUnroutineRule.getBackMoneyMode() == ActivityEnum.BackMoneyMode.FiexedAmount.getType()) {
                    if (activityUnroutineShopPlus != null) {
                    	backPoint += activityUnroutineShopPlus.getAdditionalFaceValue();
                        logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>backPoint：" + backPoint);
                    }
                } else {
                    if (activityUnroutineShopPlus != null) {
                    	backPoint = new BigDecimal(backPoint + activityUnroutineShopPlus.getAdditionalFaceValue()).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR)
                                .multiply(new BigDecimal(payAmount)).divide(new BigDecimal(100),BigDecimal.ROUND_FLOOR)
                                .divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR).intValue();
                        logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>1backPoint：" + backPoint);
                    } else {
                    	 backPoint = new BigDecimal(backPoint).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR)
                                 .multiply(new BigDecimal(payAmount)).divide(new BigDecimal(100),BigDecimal.ROUND_FLOOR)
                                 .divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR).intValue();
                    }

                    logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>2backPoint：" + backPoint);
                }


                int i = 0;
                if(backPoint >= 1) {
                    i = userSendBonus(sid, groupId, member, backPoint, tradeOfflineId, activityUnroutineRule.getActivityId());
                }

                Integer pointCurrent = member.getBonusAmount();
                Integer realPoint = 0;
                if(i == ActivityEnum.BonusSendStatus.Accounted.getType()) {
                    pointCurrent += backPoint;
                    realPoint = backPoint;
                } else if(i == ActivityEnum.BonusSendStatus.Accounting.getType()) {
                    realPoint = backPoint;
                }

//                BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(groupId);
//                bonusValue = backPoint / bonusVerifyRule.getVerifyRate();

                bonusValue = backPoint;
                logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>backPoint：" + backPoint);
                logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>bonusValue：" + bonusValue);

                //异步操作扣除营销账户，扣除已使用预算，检查活动是否结束
                if(bonusValue > 0) {
                    new Thread(new AfterRebackMoneyThread(activityUnroutineRule.getActivityId(), bonusValue, activityBaseMapper, groupAccountService,backPoint, groupId)).start();
                }

                //积分处理
                newBenefitInfo.put("point", realPoint);
                newBenefitInfo.put("pointCurrent", pointCurrent);
                logger.debug("本次消费获得积分：" + backPoint + " 剩余可用积分：" + pointCurrent);
            }

            logger.debug("------------参与活动增加次数开始-------------------------------");
            logger.debug("------------"+activityUnroutineRule.getActivityId()+"-------------------------------");
            activityBaseMapper.addAttendTimes(activityUnroutineRule.getActivityId());
        }

        if(member == null) {
            //非会员消费生成注册会员二维码(使用微信临时二维码，场景值从100000000开始)
            Integer lastSenseId = crcodeMapper.getPosMaxSenseId();
            if(lastSenseId == null) {
                lastSenseId = 1000000000;
            }
            wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupId));
            WxMpQrCodeTicket ticket = null;
            String weixinurl = null;
            try {
                ticket = this.wxService.getQrcodeService().qrCodeCreateTmpTicket(lastSenseId + 1, 2592000);
                weixinurl = this.wxService.getQrcodeService().qrCodePictureUrl(ticket.getTicket(),true);
                Crcode crcode = new Crcode();
                crcode.setGmtCreate(new Date());
                crcode.setSceneid(lastSenseId + 1);
                //非会员送权益时，userID字段保存门店ID
                crcode.setUserId(shop.getUserId());
                crcode.setQrcodePicurl(weixinurl);
                //将消费获取的权益信息保存至crcode表，用户使用微信扫码后使用场景值从表中获取要发放的权益信息
                String content = JSON.toJSONString(newBenefitInfo);
                crcode.setQrcodeLinkUrl(content);
                crcode.setQrcodeName("POS消费送");
                crcode.setStatus(1);
                crcode.setType(BizEnum.ScancrcodeType.posConsumeSend.getType());
                //非会员pos消费送时把订单号保存到qrcode字段，这样pos机重新打印小票时可以获取到这个二维码图片
                crcode.setQrcode(orderNo);
                crcode.setScanTimes(0);
                crcodeMapper.insert(crcode);
                logger.debug(content);
            } catch (WxErrorException e) {
                e.printStackTrace();
                logger.error("获取微信临时二维码失败");
            }
            newBenefitInfo.put("point_url", weixinurl);
        }
        return newBenefitInfo;
    }

    private int userSendBonus(Long sid, Long groupId, Member member, Integer backPoint, Long tradeOfflineId, Long activityId) {
        Date date = new Date();
        BonusSendRule bonusSendRule = posApiServiceCacheable.shopBonusSendRule(sid, groupId);

        if(bonusSendRule == null) {
            logger.error("未设置默认积分发放风控规则");
            return -1;
        }

        Date hourAndSecond = null;
        try {
            hourAndSecond = DateUtil.cutoutHourAndSecond(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if(hourAndSecond == null || !bonusCanSend(hourAndSecond, bonusSendRule)) {
            logger.debug("当前时段不发放积分");
            return -1;
        }

        Date dateStart = DateUtil.getDayStart(date);
        Date dateEnd = DateUtil.getAfterDay(dateStart, 1);
        Date bonusSendDate = DateUtil.getAfterHour(date, bonusSendRule.getSendAccountedTime());
        Map<String, Object> userBonusSendRecords = bonusSendLogMapper.getMemberDayBonusSendCount(member.getId(), dateStart, dateEnd);

        BonusSendLog bonusSendLog = new BonusSendLog();
        bonusSendLog.setGroupId(groupId);
        bonusSendLog.setGmtCreate(date);
        bonusSendLog.setGmtModified(date);
        bonusSendLog.setMemberId(member.getId());
        bonusSendLog.setSendType(ActivityEnum.BonusSendType.ConsumeSend.getType());
        bonusSendLog.setAdjustAmount(backPoint);
        bonusSendLog.setOrderId(tradeOfflineId);
        bonusSendLog.setShopId(sid);
        bonusSendLog.setActivityId(activityId);
        bonusSendLog.setAccountingTime(bonusSendDate);

        try {
            posApiServiceTransactional.saveSendBonus(bonusSendLog, member.getId(), backPoint, bonusSendRule, userBonusSendRecords);
        } catch (ApplicationException e) {
            e.printStackTrace();
        }
        return bonusSendLog.getAdjustStatus();
    }

    private boolean bonusCanSend(Date date, BonusSendRule bonusSendRule) {
        return bonusSendRule.getSendTimeType() == ActivityEnum.TimeRangeType.AllDay.getType() ||
                (bonusSendRule.getSendTimeFrom1() != null &&
                        bonusSendRule.getSendTimeFrom1().compareTo(date) <= 0 && bonusSendRule.getSendTimeTo1().compareTo(date) >= 0) ||
                (bonusSendRule.getSendTimeFrom2() != null &&
                        bonusSendRule.getSendTimeFrom2().compareTo(date) <= 0 && bonusSendRule.getSendTimeTo2().compareTo(date) >= 0) ||
                (bonusSendRule.getSendTimeFrom3() != null &&
                        bonusSendRule.getSendTimeFrom3().compareTo(date) <= 0 && bonusSendRule.getSendTimeTo3().compareTo(date) >= 0);
    }

    //实体卡支付/上传流水
    public Map<String, Object> icCardPay(Map<String, Object> params) {
        Integer sid = (Integer) params.get("sid");                 //商户ID
        String cardNo = (String) params.get("cardNo");              //会员卡号
        String activateCode = (String) params.get("activateCode");  //终端序列号
        String payPassword = (String) params.get("payPassword");
        String serialNum = (String) params.get("serialNum");    //终端设备序列号
        String transNo = (String) params.get("transNo");    //交易流水号
        String orderNo = (String) params.get("orderNo");

        Long t =  SysUtils.Object2Long(params.get("t"));                        //交易时间戳
        Integer payAmount = (Integer) params.get("payAmount");  //支付金额

        if(Tools.isEmpty(cardNo) || Tools.isEmpty(activateCode) || Tools.isEmpty(payPassword) || Tools.isEmpty(serialNum) || Tools.isEmpty(transNo)
                || sid == null || payAmount == null || Tools.isEmpty(orderNo)) {
            return null;
        }

        String counponSns = (String) params.get("couponSns");
        Integer couponCoverAmount = (Integer) params.get("couponCoverAmount");
        if(couponCoverAmount == null || couponCoverAmount == 0) {
            couponCoverAmount = 0;
        } else {
            if(counponSns == null) return null;
        }

        Integer pointCoverAmount = (Integer) params.get("pointCoverAmount");
        if(pointCoverAmount == null || pointCoverAmount == 0) {
            pointCoverAmount = 0;
        }

        Long shopId = (long)sid;
        Date transDate = new Date(t);
        Map<String, Object> icCardPayInfo = new HashMap<>();

        String payPasswordStr = AES.AESEncode(Const.AceKey, payPassword);
        Member member = memberMapper.checkMember(shopId, cardNo, payPasswordStr);
        if(member == null) {
            icCardPayInfo.put("responseCode", -1);
            icCardPayInfo.put("responseMsg", "支付密码错误");
            return icCardPayInfo;
        }
        
        Device device = deviceMapper.selectByserialNum(serialNum);
        System.out.print(device);
        System.out.print(shopId);
        System.out.print(device.getShopId());

        if(device==null|| !(shopId.toString().equals(device.getShopId().toString()))){
        	icCardPayInfo.put("responseCode", -1);
        	icCardPayInfo.put("responseMsg", "POS不存在");
            return icCardPayInfo; 
       }
        Long groupId=device.getGroupId();
        ShopGroupRelation shopGroupRelation=  shopGroupRelationMapper.selectShopInfo(groupId, shopId);
        if(shopGroupRelation == null) {
            return null;
        }
        String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();
       
        String payMerchantCode =shopGroupRelation.getPayMerchantCode();
       
        Shop shop = shopMapper.selectByPrimaryKey(shopId);

        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(orderNo);
        if(tradeOffline == null) { return null; }

        tradeOffline.setGmtModified(transDate);
        tradeOffline.setPayerId(member.getId());
        tradeOffline.setPayerName(member.getName());
        tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());
        tradeOffline.setReceiverId(sid.toString());
        tradeOffline.setReceiverName(shop.getMerchantName());
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        tradeOffline.setOrderAmount(payAmount + couponCoverAmount + pointCoverAmount);
        tradeOffline.setRealAmount(payAmount);
        tradeOffline.setDiscountAmount(couponCoverAmount);
        tradeOffline.setBonusAmount(pointCoverAmount);
        tradeOffline.setPayType((byte) BizEnum.PaymentType.STK.getType());
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        tradeOffline.setIsWallet(true);
        tradeOffline.setMemo("实体卡消费支付");
        tradeOffline.setTermSerial(serialNum);
        tradeOffline.setTransNo(transNo);
        tradeOffline.setTerminalNo(activateCode);
        tradeOffline.setTransOrderNo(UtilFun.createOrderNum());
        tradeOffline.setPayOrderid(tradeOffline.getTransOrderNo());

//        PayConsumption payConsumption = PayConsumption.initialize(member.getVirtualCard(), payPassword, transNo, payGroupCode, DateUtils.getDateTimeString("yyyyMMddHHmmss"),
//                tradeOffline.getTransOrderNo(),payAmount+"", 156 + "", payMerchantCode);

        try {
//            posApiServiceTransactional.saveFinishICCardConsumption(tradeOffline, payConsumption);
            PayResult payResult =walletService.updatePayConsumption(member.getVirtualCard(), payGroupCode, member.getUserId(),
					 tradeOffline.getRealAmount(), tradeOffline.getTransOrderNo(), payPassword,payMerchantCode,tradeOffline.getOrderId());
				if (!payResult.getRespCode().equals("0000")) {
					throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
				}
				tradeOffline.setTransOrderNo(payResult.getOrderId());
	        	tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            
        } catch (ApplicationException ae) {
            icCardPayInfo.put("responseCode", -1);
            icCardPayInfo.put("responseMsg", ae.errMsg);
            return icCardPayInfo;
        } catch (Exception e) {
            e.printStackTrace();
            icCardPayInfo.put("responseCode", -1);
            icCardPayInfo.put("responseMsg", "交易失败");
            return icCardPayInfo;
        }

        //核销积分

        //核销优惠券
        if(couponCoverAmount != 0) {
            String[] couponSns = counponSns.split(",");
            try {
            	for(String couponSn :couponSns){
            		activityCouponService.updateVerifyCoupon(couponSn,shopId,tradeOffline);
            	}
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //门店会员消费记录
        try {
            memberService.insertMemberTradeDataAsyn(member.getId(),payAmount,tradeOffline.getBonusValue());
        } catch (Exception e) {
            e.printStackTrace();
        }


        //会员门店关系
        memberShopRelation(member.getId(), shopId, transDate, payAmount);

        //计算新的会员权益
        icCardPayInfo = newBenefitCalc(shopId, payAmount, groupId, member, orderNo, tradeOffline.getId());
        icCardPayInfo.put("responseCode", 1);
        return icCardPayInfo;
    }


    //实体卡支付/上传流水
    public Map<String, Object> icCardPayApp(Map<String, Object> params) {
        Integer sid = (Integer) params.get("sid");                 //商户ID
        String cardNo = (String) params.get("cardNo");              //会员卡号
        String activateCode = (String) params.get("activateCode");  //终端序列号
        String payPassword = (String) params.get("payPassword");
        String serialNum = (String) params.get("serialNum");    //终端设备序列号
        String transNo = (String) params.get("transNo");    //交易流水号
        String orderNo = (String) params.get("orderNo");

        Long t =  SysUtils.Object2Long(params.get("t"));                        //交易时间戳
        Integer payAmount = (Integer) params.get("payAmount");  //支付金额

        if(Tools.isEmpty(cardNo) || Tools.isEmpty(activateCode) || Tools.isEmpty(payPassword) || Tools.isEmpty(serialNum) || Tools.isEmpty(transNo)
                || sid == null || payAmount == null || Tools.isEmpty(orderNo)) {
            return null;
        }

        String counponSns = (String) params.get("couponSns");
        Integer couponCoverAmount = (Integer) params.get("couponCoverAmount");
        if(couponCoverAmount == null || couponCoverAmount == 0) {
            couponCoverAmount = 0;
        } else {
            if(counponSns == null) return null;
        }

        Integer pointCoverAmount = (Integer) params.get("pointCoverAmount");
        if(pointCoverAmount == null || pointCoverAmount == 0) {
            pointCoverAmount = 0;
        }

        Long shopId = (long)sid;
        Date transDate = new Date(t);
        Map<String, Object> icCardPayInfo = new HashMap<>();

        String payPasswordStr = AES.AESEncode(Const.AceKey, payPassword);
        Member member = memberMapper.checkMember(shopId, cardNo, payPasswordStr);
        if(member == null) {
            icCardPayInfo.put("responseCode", -1);
            icCardPayInfo.put("responseMsg", "支付密码错误");
            return icCardPayInfo;
        }

//        Device device = deviceMapper.selectByserialNum(serialNum);
//        System.out.print(device);
//        System.out.print(shopId);
//        System.out.print(device.getShopId());
//
//        if(device==null|| !(shopId.toString().equals(device.getShopId().toString()))){
//            icCardPayInfo.put("responseCode", -1);
//            icCardPayInfo.put("responseMsg", "POS不存在");
//            return icCardPayInfo;
//        }
//        Long groupId=device.getGroupId();
        ShopGroupRelation shopGroupRelation=  shopGroupRelationMapper.selectByShopId(shopId);
        if(shopGroupRelation == null) {
            return null;
        }

        Long groupId = shopGroupRelation.getGroupId();

        String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();


        String payMerchantCode =shopGroupRelation.getPayMerchantCode();

        Shop shop = shopMapper.selectByPrimaryKey(shopId);

        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(orderNo);
        if(tradeOffline == null) { return null; }

        tradeOffline.setGmtModified(transDate);
        tradeOffline.setPayerId(member.getId());
        tradeOffline.setPayerName(member.getName());
        tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());
        tradeOffline.setReceiverId(sid.toString());
        tradeOffline.setReceiverName(shop.getMerchantName());
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        tradeOffline.setOrderAmount(payAmount + couponCoverAmount + pointCoverAmount);
        tradeOffline.setRealAmount(payAmount);
        tradeOffline.setDiscountAmount(couponCoverAmount);
        tradeOffline.setBonusAmount(pointCoverAmount);
        tradeOffline.setPayType((byte) BizEnum.PaymentType.STK.getType());
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        tradeOffline.setIsWallet(true);
        tradeOffline.setMemo("实体卡消费支付");
        tradeOffline.setTermSerial(serialNum);
        tradeOffline.setTransNo(transNo);
        tradeOffline.setTerminalNo(activateCode);
        tradeOffline.setTransOrderNo(UtilFun.createOrderNum());
        tradeOffline.setPayOrderid(tradeOffline.getTransOrderNo());

//        PayConsumption payConsumption = PayConsumption.initialize(member.getVirtualCard(), payPassword, transNo, payGroupCode, DateUtils.getDateTimeString("yyyyMMddHHmmss"),
//                tradeOffline.getTransOrderNo(),payAmount+"", 156 + "", payMerchantCode);

        try {
//            posApiServiceTransactional.saveFinishICCardConsumption(tradeOffline, payConsumption);
            PayResult payResult =walletService.updatePayConsumption(member.getVirtualCard(), payGroupCode, member.getUserId(),
                    tradeOffline.getRealAmount(), tradeOffline.getTransOrderNo(), payPassword,payMerchantCode,tradeOffline.getOrderId());
            if (!payResult.getRespCode().equals("0000")) {
                throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
            }
            tradeOffline.setTransOrderNo(payResult.getOrderId());
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

        } catch (ApplicationException ae) {
            icCardPayInfo.put("responseCode", -1);
            icCardPayInfo.put("responseMsg", ae.errMsg);
            return icCardPayInfo;
        } catch (Exception e) {
            e.printStackTrace();
            icCardPayInfo.put("responseCode", -1);
            icCardPayInfo.put("responseMsg", "交易失败");
            return icCardPayInfo;
        }

        //核销积分

        //核销优惠券
        if(couponCoverAmount != 0) {
            String[] couponSns = counponSns.split(",");
            try {
                for(String couponSn :couponSns){
                    activityCouponService.updateVerifyCoupon(couponSn,shopId,tradeOffline);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //门店会员消费记录
        try {
            memberService.insertMemberTradeDataAsyn(member.getId(),payAmount,tradeOffline.getBonusValue());
        } catch (Exception e) {
            e.printStackTrace();
        }


        //会员门店关系
        memberShopRelation(member.getId(), shopId, transDate, payAmount);

        //计算新的会员权益
        icCardPayInfo = newBenefitCalc(shopId, payAmount, groupId, member, orderNo, tradeOffline.getId());
        icCardPayInfo.put("responseCode", 1);
        return icCardPayInfo;
    }



    //门店会员关系
    public void memberShopRelation(Long memberId, Long shopId, Date transDate, Integer payAmount) {
        ShopUser shopUser = shopUserMapper.selectByMemberIdAndShopId(memberId, shopId);
        if(shopUser == null) {
            shopUser = new ShopUser();
            shopUser.setShopId(shopId);
            shopUser.setMemberId(memberId);
            shopUser.setGmtCreate(transDate);
            shopUser.setGmtModified(transDate);
            shopUser.setLastConsumTime(transDate);
            shopUser.setConsumAmount(payAmount);
            shopUser.setConsumCount(1);
            shopUser.setRefund(0);
            shopUserMapper.insertSelective(shopUser);
        } else {
            shopUser.setGmtModified(transDate);
            shopUser.setLastConsumTime(transDate);
            shopUser.setConsumAmount(shopUser.getConsumAmount() + payAmount);
            shopUser.setConsumCount(shopUser.getConsumCount() + 1);
            shopUserMapper.updateByPrimaryKeySelective(shopUser);
        }
    }

    //5.获取打印信息
    public Map<String,Object> getPrintData(Map<String, Object> params) {
        Long sid = (long)(Integer)params.get("sid");
        String clientOrderNo = (String) params.get("clientOrderNo");
        if(Tools.isEmpty(clientOrderNo)){
            return null;
        }

        Map<String, Object> printInfo = new HashMap<>();
        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(clientOrderNo);
        if(tradeOffline == null) {
            printInfo.put("responseCode", -1);
            printInfo.put("responseMsg", "请求非法");
            return printInfo;
        }

        printInfo = getBenefitInfo(tradeOffline, clientOrderNo, printInfo);

        printInfo.put("responseCode", 1);
        return printInfo;
    }

    private Map<String, Object> getBenefitInfo(TradeOffline tradeOffline, String tradeNo, Map<String, Object> result) {

        if(tradeOffline.getPayerId() == null) {
            //这里通过订单号获取到这个优惠券二维码图片重新打印
            Crcode crcode = crcodeMapper.getCouponQrcode(tradeNo);
            if(crcode != null) {
                result.put("point_url", crcode.getQrcodePicurl());
            }
        } else {
            //返现
            //获取交易记录相关的 返现交易记  //首次交易  可能会返利多条
//            TradeOffline tradeOffline1 = tradeOfflineMapper.getTradeOfflineByRelatedTradeOfflineId(tradeOffline.getId());
//            if(tradeOffline1 != null) {
//                result.put("backAmt", tradeOffline1.getRealAmount());
//            }
            List<TradeOffline> tradeOfflineList= tradeOfflineMapper.getTradeDataRelatedTradeOfflineId(tradeOffline.getId());

            if(tradeOfflineList!=null && tradeOfflineList.size()>0){
                int backAmount = 0;
                for(TradeOffline tradeOffline1 :tradeOfflineList){
                    backAmount += tradeOffline1.getRealAmount();
                }

            }


            //红包
            List<Map> couponInfos = couponUserMapper.listCouponInfoByTradeOfflineId(tradeOffline.getId());
            if(couponInfos != null && couponInfos.size() > 0) {
                List<Map<String, Object>> coupon = new ArrayList<>();
                for (int i = 0; i < couponInfos.size(); i++) {
                    Map<String, Object> coupon1 = new HashMap<>();
                    coupon1.put("coupon_name", couponInfos.get(i).get("name"));
                    coupon1.put("coupon_money", couponInfos.get(i).get("value"));
                    coupon.add(coupon1);
                }
                result.put("coupon", coupon);
            }

            //积分
            BonusSendLog bonusSendLog = bonusSendLogMapper.getByOrderId(tradeOffline.getId());
            if(bonusSendLog != null) {
                Member member = memberMapper.queryBonusAmount(tradeOffline.getPayerId());
                int bonusStatus = bonusSendLog.getAdjustStatus();
                if(bonusStatus == ActivityEnum.BonusSendStatus.Accounted.getType() ||
                        bonusStatus == ActivityEnum.BonusSendStatus.Accounting.getType()) {
                    result.put("pointCurrent", member.getBonusAmount());
                    result.put("point", bonusSendLog.getAdjustAmount());
                } else {
                    result.put("pointCurrent", member.getBonusAmount());
                    result.put("point", 0);
                }
            }
        }

        Crcode crcode = crcodeMapper.getPosRedPackageMember(tradeNo);
        if(crcode != null) {
            result.put("coupon_url", crcode.getQrcodePicurl());
        }

        return result;
    }

    //6.钱包支付
    public Map<String,Object> qbPay(Map<String, Object> params) {
        String qrCode = (String) params.get("qrCode");
        Long shopId = SysUtils.Object2Long(params.get("sid"));                 //商户ID
        String cardNo = (String) params.get("cardNo");              //会员卡号
        String activateCode = (String) params.get("activateCode");  //终端序列号
        String serialNum = (String) params.get("serialNum");    //终端设备序列号
        String transNo = (String) params.get("transNo");    //交易流水号
        String orderNo = (String) params.get("orderNo");

        Long t =  SysUtils.Object2Long(params.get("t"));                        //交易时间戳
//        Integer payAmount = (Integer) params.get("payAmount");  //支付金额
        Integer payAmount = 0;      //支付类型
        if(!Tools.isEmpty(params.get("payAmount")+"")){
            payAmount = Integer.valueOf(params.get("payAmount")+"");
        }

        if(Tools.isEmpty(cardNo) || Tools.isEmpty(activateCode) || Tools.isEmpty(qrCode) || Tools.isEmpty(serialNum) || Tools.isEmpty(transNo)
                || shopId == null || payAmount == null || Tools.isEmpty(orderNo)) {
            return null;
        }

//        Date date = new Date(t);
        Date date = new Date();

//        String counponSns = (String) params.get("couponSns");
//        Integer couponCoverAmount = (Integer) params.get("couponCoverAmount");
//        if(couponCoverAmount == null) {
//            couponCoverAmount = 0;
//        } else {
//            if(counponSns == null) return null;
//        }
//
//        Integer pointCoverAmount = (Integer) params.get("pointCoverAmount");
//        if(pointCoverAmount == null) {
//            pointCoverAmount = 0;
//        }

        Long groupId;
        String payMerchantCode;
        String payGroupCode;
        Map result = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(result == null) {
            return null;
        } else {
            groupId = (Long) result.get("groupId");
            payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();
            payMerchantCode = (String) result.get("payMerchantCode");
        }

        Member member = memberMapper.getMemberByCardNoOrPhone(shopId, cardNo);

        Long marked;
        TradeOffline tradeOffline1 = tradeOfflineMapper.Maxmarked(member.getId());
        if(tradeOffline1 == null || tradeOffline1.getMarked() == null) {
            marked = 0L;
        } else {
            marked = tradeOffline1.getMarked();
        }

        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(orderNo);
        if(tradeOffline == null) {
            tradeOffline = new TradeOffline();
            tradeOffline.setOrderId(orderNo);
            tradeOffline.setGroupId(groupId);
            tradeOffline.setGmtCreate(date);
            tradeOffline.setOrderAmount(payAmount);
            tradeOffline.setRealAmount(payAmount);
        }

        tradeOffline.setGmtModified(date);
        tradeOffline.setPayerId(member.getId());
        tradeOffline.setPayerName(member.getName());
        tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());
        tradeOffline.setReceiverId(shopId.toString());
        tradeOffline.setReceiverName((String) result.get("shopName"));
        tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
//        tradeOffline.setOrderAmount(payAmount + couponCoverAmount + pointCoverAmount);
        tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        tradeOffline.setIsWallet(true);
        tradeOffline.setMemo("用户钱包支付");
        tradeOffline.setTermSerial(serialNum);
        tradeOffline.setTransNo(transNo);
        tradeOffline.setTerminalNo(activateCode);
//        tradeOffline.setDiscountAmount(couponCoverAmount);
//        tradeOffline.setBonusAmount(pointCoverAmount);
        //这里保存用户扫码的二维码信息，可以在支付结果回调中使用二维码找到这条交易记录，更新订单号用来退款
        tradeOffline.setCrcodeStr(qrCode);

        String OrgOrderNum1 = UtilFun.createOrderNum();
        tradeOffline.setPayOrderid(OrgOrderNum1);
        tradeOffline.setMarked(marked);     //用户钱包交易 批次号


        Map<String, Object> qbPayResult = new HashMap<>();

        PayMachineQRCode payMachineQRCode = PayMachineQRCode.initialize(qrCode, OrgOrderNum1, payGroupCode, payAmount+"", transNo,
                payMerchantCode, 156 + "", DateUtils.getDateTimeString("yyyyMMddHHmmss",date));

        try {
            posApiServiceTransactional.saveFinishQbPay(tradeOffline, payMachineQRCode, shopId);

            if(member.getGroupId() !=null){
                Group group = groupMapper.selectPayCodeById(member.getGroupId());
                //更新钱包信息
                PayResult payResult =walletService.updateWallInforPosWallPay(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(),
                        tradeOffline.getRealAmount(), orderNo);

            }

        } catch (ApplicationException e) {
            System.out.println(e.getErrMsg());
            qbPayResult.put("responseCode", -1);
            qbPayResult.put("responseMsg", e.getErrMsg());
            return qbPayResult;
        } catch (Exception e) {
            e.printStackTrace();
        }

        //核销优惠券
//        if(couponCoverAmount != 0) {
//            String[] couponSn = counponSns.split(",");
//            try {
//                activityCouponService.updateVerifyCoupon(couponSn[0], shopId,tradeOffline);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

        //门店会员消费记录
        try {
            memberService.insertMemberTradeDataAsyn(member.getId(),payAmount,tradeOffline.getBonusValue());
        } catch (Exception e) {
            e.printStackTrace();
        }



        //会员门店关系
        memberShopRelation(member.getId(), shopId, date, payAmount);

        //计算新的会员权益
        qbPayResult = newBenefitCalc(shopId, payAmount, groupId, member, orderNo, tradeOffline.getId());
        qbPayResult.put("responseCode", 1);
        return qbPayResult;
    }


    //7.钱包订单查询
    public Map<String,Object> qbQuery(Map<String, Object> params) {
//        Integer merchantId = (Integer) params.get("MerchantId");
//        String terminalNo = (String) params.get("TerminalNo");
//        String orgTranDateTime = (String) params.get("OrgTranDateTime");
//        String operatorNum = (String) params.get("operator_num");
        String orgOrderNum = (String) params.get("OrgOrderNum");
        if(Tools.isEmpty(orgOrderNum)) {
            return null;
        }

        Map<String, Object> qbQuery = new HashMap<>();
        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(orgOrderNum);
        if(tradeOffline == null) {
            qbQuery.put("responseMsg", "订单不存在");
            qbQuery.put("responseCode", -1);
            } else {
            qbQuery = getBenefitInfo(tradeOffline, orgOrderNum, qbQuery);
            qbQuery.put("responseCode", 1);
        }
        return qbQuery;
    }

    //8.钱包退款
    public Map<String,Object> tradePacketCancel(Map<String, Object> params) {
//        String payType = (String) params.get("payType");
//        String action = (String) params.get("action");
//        Integer sidStr = (Integer) params.get("sid");
//        String operatorNum = (String) params.get("operator_num");
        String oldTradeOrderNum = (String) params.get("old_trade_order_num");
        String newTradeOrderNum = (String) params.get("new_trade_order_num");

        logger.info("+++++++++++++++新订单号++++++++++++"+newTradeOrderNum);
        logger.info("+++++++++++++++老订单号++++++++++++"+oldTradeOrderNum);
        if(Tools.isEmpty(oldTradeOrderNum) || Tools.isEmpty(newTradeOrderNum)) { return null; }

        Map<String, Object> walletRefundInfo = new HashMap<>();

        //原交易记录
        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(oldTradeOrderNum);
        if(tradeOffline == null) {
            walletRefundInfo.put("responseCode", -1);
            walletRefundInfo.put("responseMsg", "原订单不存在");
            return walletRefundInfo;
        }

        Long groupId;
        String payMerchantCode;
        String payGroupCode;
        Map result = shopGroupRelationMapper.selectShopInfoByShopId(Long.parseLong(tradeOffline.getReceiverId()));
        if(result == null) {
            return null;
        } else {
            groupId = (Long) result.get("groupId");
            payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();
            payMerchantCode = (String) result.get("payMerchantCode");
        }

        Member member = memberMapper.selectByPrimaryKey(tradeOffline.getPayerId());
        Date date = new Date();
        //创建交易记录
        TradeOffline tradeOffline1 = new TradeOffline();
        tradeOffline1.setIsWallet(true);
        tradeOffline1.setOrderId(newTradeOrderNum);
        tradeOffline1.setOldOrderId(tradeOffline.getId());
        tradeOffline1.setGroupId(tradeOffline.getGroupId());
        tradeOffline1.setTransactionType((byte) BizEnum.TransactionType.Refund.getType());
        tradeOffline1.setPayType((byte) 13);
        tradeOffline1.setGmtCreate(date);
        tradeOffline1.setGmtModified(date);
        tradeOffline1.setTransactionStatus((byte) BizEnum.TransactionStatus.Refund.getType());
        tradeOffline1.setOrderAmount(-(tradeOffline.getOrderAmount()));
        tradeOffline1.setRealAmount(-(tradeOffline.getRealAmount()));
//        tradeOffline1.setDiscountAmount(-(tradeOffline.getDiscountAmount()));
        tradeOffline1.setBonusValue(-(tradeOffline.getBonusValue()));
        tradeOffline1.setBonusAmount(-(tradeOffline.getBonusAmount()));
        tradeOffline1.setPayerId(tradeOffline.getPayerId());
        tradeOffline1.setPayerType(tradeOffline.getPayerType());
        tradeOffline1.setPayerName(tradeOffline.getPayerName());
        tradeOffline1.setReceiverId(tradeOffline.getReceiverId());
        tradeOffline1.setReceiverName(tradeOffline.getReceiverName());

        String orderNo = UtilFun.createOrderNum();
        UnPayConsumption unPayConsumption = UnPayConsumption.initialize(member.getVirtualCard(), payMerchantCode, payGroupCode,
                tradeOffline.getRealAmount().toString(), tradeOffline.getTransOrderNo(), orderNo, DateUtils.getDateTimeString("yyyyMMddHHmmss"), AES.AESDncode(Const.AceKey, member.getTradePassword()),
                UtilFun.createRandomNum(10),156+"");

        try {
            posApiServiceTransactional.saveQbRefund(member.getId(), tradeOffline1, unPayConsumption, tradeOffline.getId(), tradeOffline.getBonusAmount(),tradeOffline.getRealAmount());
            //退款更新会员统计表的的消费总额 跟笔数  会员升级金额 相应减掉
            memberService.updateStatisMemberInfo(tradeOffline.getPayerId(),tradeOffline.getRealAmount());
            //如果使用了积分核销结算到门店的积分退回
            BonusVerifyLog bonusVerifyLog=bonusVerifyLogMapper.queryBonusVerifyLogByTradeId(tradeOffline.getId());
            //核销门店退回得到的结算积分
            if(bonusVerifyLog !=null){
                bonusVerifyShopMapper.updateShopBonusInfo(bonusVerifyLog.getShopId(),bonusVerifyLog.getSettingAmount());
            }


        } catch (ApplicationException e) {
            walletRefundInfo.put("responseCode", -1);
            walletRefundInfo.put("responseMsg", "退款处理失败");
            return walletRefundInfo;
        }

    //    refundBenefit(tradeOffline, groupId, payGroupCode, member, newTradeOrderNum);
        try {
			refundBenefit(tradeOffline,newTradeOrderNum);
		} catch (ApplicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

        walletRefundInfo.put("responseMsg", "退款处理成功");
        walletRefundInfo.put("responseCode", 1);
        return walletRefundInfo;
    }

    //9.其他交易退款
    public Map<String,Object> tradeCancel(Map<String, Object> params) {

        String oldTradeOrderNum = (String) params.get("old_trade_order_num");
        String newTradeOrderNum = (String) params.get("new_trade_order_num");
        String authCode = (String) params.get("authCode");
        Integer sid = (Integer) params.get("sid");

//      long t = SysUtils.Object2Long(params.get("t"));
        String action = (String) params.get("action");
        int payType = (Integer) params.get("payType");
//      String operatorNum = (String) params.get("operator_num");

        switch (payType) {
            case 10:
                payType = 6;
                break;
            case 11:
                payType = 3;
                break;
            case 12:
                payType = 1;
                break;
            case 25:
                payType = 25;
                break;
            case 27:
                payType = 27;
                break;
            default:
                payType = 99;
                break;
        }

        if(Tools.isEmpty(oldTradeOrderNum) || Tools.isEmpty(newTradeOrderNum) || Tools.isEmpty(authCode) || Tools.isEmpty(action)) {
            return null;
        }

        Map<String, Object> otherRefundInfo = new HashMap<>();
        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(oldTradeOrderNum);
        if(tradeOffline == null) {
            otherRefundInfo.put("responseCode", -1);
            otherRefundInfo.put("responseMsg", "未获取到原订单信息");
            return otherRefundInfo;
        }


        Long shopId = (long) sid;

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

//        Date date = new Date();
//        Long groupId = (Long) shopInfo.get("groupId");

        try {
            posApiServiceTransactional.saveOtherRefund(newTradeOrderNum, authCode, payType, tradeOffline);

            //退款更新会员统计表的的消费总额 跟笔数  相应减掉 会员升级金额
            if(tradeOffline.getPayerId()!=null){
                memberService.updateStatisMemberInfo(tradeOffline.getPayerId(),tradeOffline.getRealAmount());
            }
        } catch (ApplicationException e) {
            e.printStackTrace();
            otherRefundInfo.put("responseCode", -1);
            otherRefundInfo.put("responseMsg", "服务器处理错误");
            return otherRefundInfo;
        }

        if(tradeOffline.getPayerId() != null) {
            try {
				refundBenefit(tradeOffline,newTradeOrderNum);
			} catch (ApplicationException e) {
				e.printStackTrace();
			}
        }

        otherRefundInfo.put("responseCode", 1);
        otherRefundInfo.put("responseMsg", "退款处理成功");
        return otherRefundInfo;
    }

    /**
     * 退回已获得红包 优惠券 积分等信息
     * @param tradeOffline
     * @param newTradeOrderNum
     * @throws ApplicationException
     */
    public void refundBenefit(TradeOffline tradeOffline, String newTradeOrderNum) throws ApplicationException {
        Date date = new Date();
        long tradeOfflineId = tradeOffline.getId();
        Member member =memberMapper.queryGroup(tradeOffline.getPayerId());
        if(member==null){
        	return;
        } 
        
        String payGroupCode=member.getPayGroupCode();
        Long groupId=member.getGroupId();
        
        //原交易获的的优惠券退回
        logger.info(">>>>>>>>退款时更改优惠券的状态>>>>>>>>>>");
        logger.info(">>>>>>>>退款时更改优惠券的核销张数>>>>>>>>>>");
        logger.info(">>>>>>>>订单号>>>>>>>>>>"+tradeOffline.getOrderId());
        if(tradeOffline.getOrderId().startsWith(Const.CONSUMPTION_REAL) && tradeOffline.getBonusValue()>0){
            //线上交易  couponUser orderId对应的是orderGood表中的主键id
            OrderGood orderGood = orderGoodMapper.queryOrderGoodInfoByOrderNo(tradeOffline.getOrderId());

//        couponUserMapper.refundUserCouponByTradeOfflineId(tradeOfflineId);
            couponUserMapper.refundUserCouponByTradeOfflineId(orderGood.getId());
            CouponUser couponUser =couponUserMapper.queryCouponIdByTradeId(orderGood.getId());
            if (couponUser !=null) {
                couponMapper.updateCouponcount(couponUser.getCouponId());
            }
        }else if(tradeOffline.getOrderId().startsWith(Const.CONSUMPTION_VIRTUAL) && tradeOffline.getBonusValue()>0){

            //服务商品  couponUser orderId对应的是tradeOffline表中的主键id
            couponUserMapper.refundUserCouponByTradeOfflineId(tradeOfflineId);
            CouponUser couponUser =couponUserMapper.queryCouponIdByTradeId(tradeOfflineId);
            if (couponUser !=null) {
                couponMapper.updateCouponcount(couponUser.getCouponId());
            }
            logger.info("服务商品退回优惠券");
        }else{
            couponUserMapper.refundUserCouponByTradeOfflineId(tradeOfflineId);
        }


        //原交易获的的红包退回
        RedpackageUser redpackageUser = redpackageUserMapper.getRedPackageUserByTradeOfflineId(tradeOfflineId);
        if(redpackageUser != null) {
            if(redpackageUser.getGetStatus() == ActivityEnum.RedpackageGetStatus.Gotten.getType()) {
                TradeOffline tradeOffline2 = new TradeOffline();
                tradeOffline2.setGroupId(groupId);
                tradeOffline2.setOrderId(newTradeOrderNum);
                tradeOffline2.setIsWallet(true);
                tradeOffline2.setGmtCreate(date);
                tradeOffline2.setGmtModified(date);
                tradeOffline2.setPayerId(tradeOffline.getPayerId());
                tradeOffline2.setPayerType(tradeOffline.getPayerType());
                tradeOffline2.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
                tradeOffline2.setPayerName(tradeOffline.getPayerName());
                tradeOffline2.setRealAmount(-(redpackageUser.getRealAmount()));
                tradeOffline2.setOldOrderId(redpackageUser.getTradeOfflineId());
                tradeOffline2.setTransactionType((byte) BizEnum.TransactionType.AddBalance.getType());
                tradeOffline2.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
                tradeOffline2.setMemo("用户已领取红包退回");

                String OrgOrderNum = UtilFun.createOrderNum();
                tradeOffline2.setPayOrderid(OrgOrderNum);
//              PayBalanceChange payBalanceChange = PayBalanceChange.initialize(payGroupCode, member.getVirtualCard(), tradeOffline2.getRealAmount().toString(), "0", OrgOrderNum,
//                        DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createRandomNum(10), "156");
                try {
//                   posApiServiceTransactional.saveRefundUserRedpackage(tradeOffline2, payBalanceChange);
                	PayResult flag=walletService.updateUserLockedAmount(member.getVirtualCard(), payGroupCode, member.getUserId(), "-"+tradeOffline2.getRealAmount(), "0", 0,newTradeOrderNum);
                    if(flag==null){
		            	throw new ApplicationException("用户已领取红包退回失败");
		            }
                    
                } catch (ApplicationException e) {
                    e.printStackTrace();
                    logger.error(e.errMsg);
                }
            }
            redpackageUser.setGetStatus(ActivityEnum.RedpackageGetStatus.Refunded.getType());
            redpackageUserMapper.updateByPrimaryKeySelective(redpackageUser);
        }

        //原交易获的的积分退回
        BonusSendLog bonusSendLog = bonusSendLogMapper.getByOrderId(tradeOffline.getId());
        if(bonusSendLog != null) {
            try {
                posApiServiceTransactional.saveMemberBonusRefund(bonusSendLog, member);
            } catch (ApplicationException e) {
                e.printStackTrace();
            }
        }

        //原交易获的的返现退回
        //消费返现的交易记录

//        TradeOffline tradeOffline3 = tradeOfflineMapper.getTradeOfflineByRelatedTradeOfflineId(tradeOffline.getId());
        TradeOffline tradeOffline3 = tradeOfflineMapper.getTradeDataByRelatedTradeOfflineId(tradeOffline.getId(),member.getId().toString());
        if(tradeOffline3 != null) {

            tradeOffline3.setOrderAmount(-1*tradeOffline3.getOrderAmount());
            tradeOffline3.setRealAmount(-1*tradeOffline3.getRealAmount());
            tradeOffline3.setGmtModified(tradeOffline3.getGmtModified());
            tradeOffline3.setTransactionStatus((byte) BizEnum.TransactionStatus.ISRefund.getType());
            tradeOffline3.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline3);

            try {
            	PayResult flag=walletService.updateUserLockedAmount(member.getVirtualCard(), payGroupCode, member.getUserId(), tradeOffline3.getRealAmount()+"", "0", 0,tradeOffline3.getOrderId());
                if(flag==null){
	            	throw new ApplicationException("用户返利退回失败");
	            }
                
            } catch (ApplicationException e) {
                e.printStackTrace();
                logger.error(e.errMsg);
            }
        }
    }

    /*
    * 10.交接
    * */
    public Map<String,Object> shiftTime(Map<String, Object> params) {
        Long sid = SysUtils.Object2Long(params.get("sid"));
        Long start_time = SysUtils.Object2Long(params.get("start_time"));
        Long end_time = SysUtils.Object2Long(params.get("end_time"));

        Date dateStart = new Date(start_time*1000);
        Date dateEnd = new Date(end_time*1000);

        Map<String, Object> empty = new HashMap<>();
        empty.put("trade_num",0);
        empty.put("real_pay_money", 0);
        empty.put("coupon_deduct", 0);
        empty.put("intergral_deduct", 0);
        empty.put("real_undo_money", 0);

        Map<String, Object> shiftTimeInfo = new HashMap<>();

        List<Map<String, Object>> tradeInfo = tradeOfflineMapper.statisticByTime(sid, dateStart, dateEnd);
        List<Map<String, Object>> refundInfo = tradeOfflineMapper.statisticRefundByTime(sid, dateStart, dateEnd);

        for(int i = 0; i < tradeInfo.size(); i++) {
            int payType = (Integer) tradeInfo.get(i).get("payType");
            switch (payType) {
                case 7:
                    shiftTimeInfo.put("pay_cash", tradeInfo.get(i));
                    break;
                case 6:
                    shiftTimeInfo.put("pay_swipe", tradeInfo.get(i));
                    break;
                case 3:
                    shiftTimeInfo.put("pay_wx", tradeInfo.get(i));
                    break;
                case 1:
                    shiftTimeInfo.put("pay_aly", tradeInfo.get(i));
                    break;
                case 13:
                    shiftTimeInfo.put("pay_qb", tradeInfo.get(i));
                    break;
            }
        }

        for(int i = 0; i < refundInfo.size(); i++) {
            int payType = (int) refundInfo.get(i).get("payType");
            switch (payType) {
                case 6:
                    shiftTimeInfo.put("pay_unswipe", refundInfo.get(i));
                    break;
                case 3:
                    shiftTimeInfo.put("pay_unwx", refundInfo.get(i));
                    break;
                case 1:
                    shiftTimeInfo.put("pay_unaly", refundInfo.get(i));
                    break;
                case 13:
                    shiftTimeInfo.put("pay_unqb", refundInfo.get(i));
                    break;
            }
        }

        String[] results = {"pay_cash", "pay_swipe", "pay_wx", "pay_aly", "pay_qb", "pay_unswipe", "pay_unwx", "pay_unaly", "pay_unqb"};
        for(int i = 0; i < results.length; i++) {
            if(!shiftTimeInfo.containsKey(results[i])) {
                shiftTimeInfo.put(results[i], empty);
            }
        }

        Map<String, Object> total = tradeOfflineMapper.statisticByTimeAll(sid, dateStart, dateEnd);
        total.putAll(tradeOfflineMapper.statisticRefundByTimeAll(sid, dateStart, dateEnd));

        shiftTimeInfo.put("total", total);
        shiftTimeInfo.put("responseCode", 1);
        return shiftTimeInfo;
    }

    /*
    * 开卡/绑卡(记名,暂时未用)
    * */
    public Map<String,Object> newCard(Map<String, Object> params) {
        String username = (String) params.get("username");
        String mobile = (String) params.get("mobile");
        String icCardNo = (String) params.get("icCardNo");
        Integer sid = (Integer) params.get("sid");

        Date date = new Date();

        if(Tools.isEmpty(mobile) || Tools.isEmpty(icCardNo) || sid == null) {
            return null;
        }

        Long shopId = (long) sid;

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");

        Map<String, Object> newCardInfo = new HashMap<>();

        Member member = memberMapper.checkMemberByMobileAndShopId(groupId, mobile);
        if(member != null && member.getIccardNo() != null) {
            if(member.getIccardNo().equals(icCardNo)) {
                newCardInfo.put("resCode", 10);
                newCardInfo.put("resMsg", "手机号码和该卡已绑定");
            } else {
                newCardInfo.put("resCode", 20);
                newCardInfo.put("resMsg", "手机号码已绑定其他卡");
                newCardInfo.put("oldICCardNo", member.getIccardNo());
            }
        } else if(member != null && member.getIccardNo() == null) {
            MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
            memberICCardInfo.setMemberId(member.getId());
            memberICCardInfo.setIccardNo(icCardNo);
            memberICCardInfo.setGmtCreate(date);
            memberICCardInfo.setStatus(BizEnum.ICCardStatus.Bounded.getType());
            int i = memberICCardInfoMapper.insertSelective(memberICCardInfo);
            if(i != 1) {
                newCardInfo.put("responseCode", -1);
                newCardInfo.put("responseMsg", "服务器处理错误");
                return newCardInfo;
            }
            newCardInfo.put("resCode", 1);
            newCardInfo.put("resMsg", "绑卡成功");
        } else {
            Group group = groupMapper.selectByPrimaryKey(groupId);
            String virtualCardNO = "" + group.getPayGroupCode() + sid + (new Date().getTime()+"").substring(0, 10);

            PayUserAccounts payUserAccounts = PayUserAccounts.initialize(group.getPayGroupCode(), virtualCardNO, "000", "000000000000000000",
                    "888888", "000000", "000000", "000@163.com","00000000000", null, DateUtils.getDateTimeString("yyyyMMddHHmmss"),null);

            Userbase userbase = new Userbase();
            userbase.setGroupId(groupId);
            userbase.setGmtCreate(date);
            userbase.setStatus(BizEnum.UserStatus.Normal.getType());
            userbase.setUserType(CommonEnum.UserType.User.getType());

            member = new Member();
            member.setGroupId(groupId);
            member.setName(username);
            member.setCardNo(DateUtil.getMonth()+Tools.getRandomNum(6));
            member.setPhone(mobile);
            member.setTradePassword(AES.AESEncode(Const.AceKey, "888888"));
            member.setFromType(BizEnum.MemberDevelopeFrom.ShopDevelope.getType());
            member.setFromId(shopId);
            member.setFromName((String) shopInfo.get("shopName"));
            member.setFromMode(BizEnum.MemberDevelopeMode.PosConsume.getType());
            member.setWalletStatus(1);
//            member.setWalletStatus(CommonEnum.WalletStatus.close.getType() == 1);
            member.setVirtualCard(virtualCardNO);
            member.setGmtCreate(date);

            MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
            memberICCardInfo.setGmtCreate(date);
            memberICCardInfo.setIccardNo(icCardNo);

            try {
                posApiServiceTransactional.saveMemberICCard(userbase, member, memberICCardInfo, payUserAccounts);
            } catch (Exception e) {
                e.printStackTrace();
                newCardInfo.put("responseCode", -1);
                newCardInfo.put("responseMsg", "服务器处理错误");
                return newCardInfo;
            }

            newCardInfo.put("resCode", 2);
            newCardInfo.put("resMsg", "开卡成功");
        }
        newCardInfo.put("responseCode", 1);
        return newCardInfo;
    }

    /*
    * 开卡绑卡（不记名）
    * */
    public Map<String,Object> newCard1(Map<String, Object> params) {
        String username = (String) params.get("username");
        String mobile = (String) params.get("mobile");
        String icCardNo = (String) params.get("icCardNo");
        Integer sid = (Integer) params.get("sid");

        Date date = new Date();

        if(Tools.isEmpty(icCardNo) || sid == null) {
            return null;
        }

        Long shopId = (long) sid;

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");

        Map<String, Object> newCardInfo = new HashMap<>();
        Member member = null;

        if(!Tools.isEmpty(mobile)) {
            MemberICCardInfo memberICCardInfo = memberICCardInfoMapper.getByICCardNo(mobile);
            if(memberICCardInfo != null && memberICCardInfo.getStatus().equals(BizEnum.ICCardStatus.Abandon.getType())) {
                newCardInfo.put("resCode", 10);
                newCardInfo.put("resMsg", "卡已废弃不能在使用");
                newCardInfo.put("responseCode", 1);
                return newCardInfo;
            }

            member = memberMapper.checkMemberByMobileAndShopId(groupId, mobile);
            if(member != null) {
                if(member.getIccardNo() != null) {
                    if(member.getIccardNo().equals(icCardNo)) {
                        newCardInfo.put("resCode", 10);
                        newCardInfo.put("resMsg", "手机号码和该卡已绑定");
                    } else {
                        newCardInfo.put("resCode", 20);
                        newCardInfo.put("resMsg", "手机号码已绑定其他卡");
                        newCardInfo.put("oldICCardNo", member.getIccardNo());
                    }
                    newCardInfo.put("responseCode", 1);
                    return newCardInfo;
                } else if(member.getIccardNo() == null) {
                    Member member1 = memberICCardInfoMapper.getMemberByICCardNo(icCardNo);
                    if(member1 == null) {
                        newCardInfo.put("resCode", 100);
                        newCardInfo.put("resMsg", "是否绑定该卡");
                    } else {
                        newCardInfo.put("resCode", 30);
                        newCardInfo.put("resMsg", "实体卡已绑定其他账户");
                    }
                    newCardInfo.put("responseCode", 1);
                    return newCardInfo;
                }
            }
        }

        Group group = groupMapper.selectByPrimaryKey(groupId);
        String virtualCardNO = "" + group.getPayGroupCode() + sid + (new Date().getTime()+"").substring(0, 10);

        PayUserAccounts payUserAccounts = PayUserAccounts.initialize(group.getPayGroupCode(), virtualCardNO, "000", "000000000000000000",
        		"888888", "000000", "000000", "000@163.com","00000000000", null, DateUtils.getDateTimeString("yyyyMMddHHmmss"),null);

        Userbase userbase = new Userbase();
        userbase.setGroupId(groupId);
        userbase.setGmtCreate(date);
        userbase.setStatus(BizEnum.UserStatus.Normal.getType());
        userbase.setUserType(CommonEnum.UserType.User.getType());

   //     MemberGrade memberGrade = memberGradeMapper.selectMemberGradeByGroupIdAndGradeName(groupId, BizEnum.MemberGradeDefault.unattention.getName());
        
        List<MemberGrade> memberGradeList=memberGradeMapper.selectGroupList(groupId);

        member = new Member();
        member.setGroupId(groupId);
        member.setName(username);
        member.setCardNo(DateUtil.getMonth()+Tools.getRandomNum(6));
        member.setPhone(mobile);
        member.setTradePassword(AES.AESEncode(Const.AceKey, "888888"));
        member.setFromType(BizEnum.MemberDevelopeFrom.ShopDevelope.getType());
        member.setFromId(shopId);
        member.setFromName((String) shopInfo.get("shopName"));
        member.setFromMode(BizEnum.MemberDevelopeMode.PosConsume.getType());
        member.setWalletStatus(1);
//        member.setWalletStatus(CommonEnum.WalletStatus.close.getType() == 1);
        member.setVirtualCard(virtualCardNO);
        member.setGmtCreate(date);
        member.setIccardNo(icCardNo);
        
        if(memberGradeList.size()>1){
        	//取值第二个会员id
        	member.setGradeId(memberGradeList.get(1).getId());
        }
        
        
        member.setWalletStatus(1);

        MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
        memberICCardInfo.setGmtCreate(date);
        memberICCardInfo.setIccardNo(icCardNo);
        memberICCardInfo.setStatus(BizEnum.ICCardStatus.Bounded.getType());

        try {
            posApiServiceTransactional.saveMemberICCard(userbase, member, memberICCardInfo, payUserAccounts);
        } catch (Exception e) {
            e.printStackTrace();
            newCardInfo.put("responseCode", -1);
            newCardInfo.put("responseMsg", "服务器处理错误");
            return newCardInfo;
        }

        newCardInfo.put("resCode", 2);
        newCardInfo.put("resMsg", "开卡成功");

        newCardInfo.put("responseCode", 1);
        return newCardInfo;
    }

    /*
    * 确认绑卡
    * */
    public Map<String, Object> confirmBindCard(Map<String, Object> params) {
        String mobile = (String) params.get("mobile");
        String icCardNo = (String) params.get("icCardNo");
        Integer sid = (Integer) params.get("sid");

        if(Tools.isEmpty(mobile) || Tools.isEmpty(icCardNo) || sid == null) {
            return null;
        }

        Long shopId = (long) sid;

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");

        Member member = memberMapper.checkMemberByMobileAndShopId(groupId, mobile);

        MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
        memberICCardInfo.setGmtCreate(new Date());
        memberICCardInfo.setIccardNo(icCardNo);
        memberICCardInfo.setStatus(BizEnum.ICCardStatus.Bounded.getType());
        memberICCardInfo.setMemberId(member.getId());

        Map<String, Object> confirmBindCardInfo = new HashMap<>();
        int i = memberICCardInfoMapper.insertSelective(memberICCardInfo);
        if(i != 1) {
            confirmBindCardInfo.put("responseCode", -1);
            confirmBindCardInfo.put("responseMsg", "服务器处理错误");
            return confirmBindCardInfo;
        }

        confirmBindCardInfo.put("responseCode", 1);
        confirmBindCardInfo.put("resCode", 1);
        confirmBindCardInfo.put("resMsg", "绑卡成功");
        return confirmBindCardInfo;
    }


    /*
    * 换卡
    * */
    public Map<String, Object> changeCard(Map<String, Object> params) {
        String username = (String) params.get("username");
        String mobile = (String) params.get("mobile");
        String icCardNo = (String) params.get("icCardNo");
        Integer sid = (Integer) params.get("sid");

        Date date = new Date();

        if(Tools.isEmpty(mobile) || Tools.isEmpty(icCardNo) || sid == null) {
            return null;
        }

        Long shopId = (long) sid;

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");
        Map<String, Object> changeCardInfo = new HashMap<>();

        Member member = memberMapper.checkMemberByMobileAndShopId(groupId, mobile);
        if(member == null) {
            changeCardInfo.put("resCode", 10);
            changeCardInfo.put("resMsg", "用户信息不存在");
        } else {
            MemberICCardInfo memberICCardInfo1 = memberICCardInfoMapper.getByICCardNo(icCardNo);
            if(memberICCardInfo1 != null) {
                if(memberICCardInfo1.getStatus().equals(BizEnum.ICCardStatus.Abandon.getType())) {
                    changeCardInfo.put("resCode", 10);
                    changeCardInfo.put("resMsg", "卡已废弃不能在使用");
                } else if(memberICCardInfo1.getStatus().equals(BizEnum.ICCardStatus.Bounded.getType())) {
                    changeCardInfo.put("resCode", 12);
                    changeCardInfo.put("resMsg", "卡已在使用中");
                } else {
                    changeCardInfo.put("resCode", 13);
                    changeCardInfo.put("resMsg", "卡信息已存在");
                }
                changeCardInfo.put("responseCode", 1);
                return changeCardInfo;
            }

            MemberICCardInfo memberICCardInfo = new MemberICCardInfo();
            memberICCardInfo.setMemberId(member.getId());
            memberICCardInfo.setStatus(BizEnum.ICCardStatus.Bounded.getType());
            memberICCardInfo.setIccardNo(icCardNo);
            memberICCardInfo.setGmtCreate(date);
            memberICCardInfo.setGmtModified(date);

            try {
                posApiServiceTransactional.saveChangeCard(member.getId(), memberICCardInfo);
            } catch (ApplicationException e) {
                System.out.println("============================" + e.getErrMsg());
                changeCardInfo.put("responseCode", -1);
                changeCardInfo.put("responseMsg", e.getErrMsg());
                return changeCardInfo;
            }

            changeCardInfo.put("resCode", 1);
            changeCardInfo.put("resMsg", "换卡成功");
        }

        changeCardInfo.put("responseCode", 1);
        return changeCardInfo;
    }


    /*
    * 获取充值活动信息
    * */
    public Map<String, Object> getRechargeInfo(Map<String, Object> params) {
        Integer sid = (Integer) params.get("sid");
        if(sid == null) {
            return null;
        }

        Long shopId = (long) sid;
        Date date = new Date();

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");
        ActivityUnroutine activityUnroutine = activityUnroutineMapper.getCurrentRechargeActivite(groupId, date);

        Map<String, Object> getRechargeInfo = new HashMap<>();
        if(activityUnroutine == null) {
            getRechargeInfo.put("rechargeType", 3);
        } else {
//            ActivityUnroutineInDTO activityUnroutineInDTO = new ActivityUnroutineInDTO();
//            activityUnroutineInDTO.setId(activityUnroutine.getActivityId());
//            List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.selectActivityUnroutineRule(activityUnroutineInDTO);

            List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.selectActivityUnroutineRule(activityUnroutine.getActivityId());
            List<Map<String, Object>> combineInfo = new ArrayList<>();
            for(int i = 0; i < activityUnroutineRuleList.size(); i++) {
                Map<String, Object> combine = new HashMap<>();
                ActivityUnroutineRule aur = activityUnroutineRuleList.get(i);
                combine.put("bid", aur.getId());
                combine.put("real_pay_money", aur.getMiniAmount());
                combine.put("real_get_money", aur.getFaceValue());
                combineInfo.add(combine);
            }
            if(activityUnroutineRuleList.get(0).getBackMoneyMode() == ActivityEnum.BackMoneyMode.FiexedAmount.getType()) {
                getRechargeInfo.put("rechargeType", 1);
                getRechargeInfo.put("combineInfo", combineInfo);
            } else if(activityUnroutineRuleList.get(0).getBackMoneyMode() == ActivityEnum.BackMoneyMode.Percentage.getType()){
                getRechargeInfo.put("rechargeType", 2);
                getRechargeInfo.put("percentageInfo", combineInfo);
            } else {
                getRechargeInfo.put("rechargeType", 3);
                getRechargeInfo.put("percentageInfo", combineInfo);
            }
        }
        getRechargeInfo.put("responseCode", 1);
        return getRechargeInfo;
    }

    /*
    * 充值金额计算
    * */
    public Map<String,Object> rechargeAmountQuery(Map<String, Object> params) {
        Integer sid = (Integer) params.get("sid");
        Integer payAmount = (Integer) params.get("payAmount");
        String orderNo = (String) params.get("orderNo");
        String mobile = (String) params.get("mobile");

        if(sid == null || payAmount == null || Tools.isEmpty(orderNo) || Tools.isEmpty(mobile)) {
            return null;
        }

        Map<String, Object> rechargeInfo = new HashMap<>();
        Date date = new Date();

        Long shopId = (long) sid;

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");
//        String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();
//        String payMerchantCode = (String) shopInfo.get("payMerchantCode");
//        if(groupId == null || payMerchantCode == null) {
//            return null;
//        }

        Member member = memberMapper.getMemberByICCardNoOrPhone(mobile, groupId);

        if(member == null) {
            rechargeInfo.put("responseCode", -1);
            rechargeInfo.put("responseMsg", "账号不存在");
            return rechargeInfo;
        }

        MemberICCardInfo memberICCardInfo = memberICCardInfoMapper.getBoundICCardByMemberId(member.getId());
        /*if(memberICCardInfo == null) {
            rechargeInfo.put("responseCode", -1);
            rechargeInfo.put("responseMsg", "用户还未绑定实体卡");
            return rechargeInfo;
        }*/

//        //查询商户余额
//        PayBalanceQuery payBalanceQuery = PayBalanceQuery.initialize(payMerchantCode, payGroupCode, UtilFun.createRandomNum(10),
//                DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createOrderNum());
//        PayBalanceResult payBalanceResult = IPayAPI.accountBalanceQuery(payBalanceQuery, true);
//        if(Integer.parseInt(payBalanceResult.getCurBal()) < payAmount) {
//            rechargeInfo.put("responseCode", -1);
//            rechargeInfo.put("responseMsg", "商户余额不足");
//            return rechargeInfo;
//        }

        //到账金额计算
        ActivityUnroutine activityUnroutine = activityUnroutineMapper.getCurrentRechargeActivite(groupId, date);
        if(activityUnroutine == null) {
            rechargeInfo.put("actualAmount", payAmount);
        } else {
//            ActivityUnroutineInDTO activityUnroutineInDTO = new ActivityUnroutineInDTO();
//            activityUnroutineInDTO.setId(activityUnroutine.getActivityId());
//            List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.selectActivityUnroutineRule(activityUnroutineInDTO);

            List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.selectActivityUnroutineRule(activityUnroutine.getActivityId());
            if(activityUnroutineRuleList.get(0).getBackMoneyMode() == ActivityEnum.BackMoneyMode.FiexedAmount.getType()) {
                for(int i = 0; i < activityUnroutineRuleList.size(); i++) {
                    ActivityUnroutineRule aur = activityUnroutineRuleList.get(i);
                    if(aur.getMiniAmount().equals(payAmount)) {
                        rechargeInfo.put("actualAmount", payAmount + aur.getFaceValue());
                        break;
                    }
                }
                if(rechargeInfo.get("actualAmount") == null) {
                    rechargeInfo.put("responseCode", -1);
                    rechargeInfo.put("responseMsg", "充值金额不正确");
                    return rechargeInfo;
                }
            } else {
                activityUnroutineRuleList.sort(new Comparator<ActivityUnroutineRule>() {
                    @Override
                    public int compare(ActivityUnroutineRule o1, ActivityUnroutineRule o2) {
                        return o2.getMiniAmount() - o1.getMiniAmount();
                    }
                });
                for(int i = 0; i < activityUnroutineRuleList.size(); i++) {
                    ActivityUnroutineRule aur = activityUnroutineRuleList.get(i);
                    if(aur.getMiniAmount() <= payAmount) {
                        BigDecimal percentage = new BigDecimal(aur.getFaceValue()).divide(new BigDecimal(10000), 2, BigDecimal.ROUND_FLOOR);
                        Integer actualAmount = new BigDecimal(payAmount).multiply(percentage.add(new BigDecimal(1))).intValue();
                        rechargeInfo.put("actualAmount", actualAmount);
                        break;
                    }
                }
                rechargeInfo.putIfAbsent("actualAmount", payAmount);
            }
        }

        //流水记录创建
        TradeOffline tradeOffline = new TradeOffline();
        tradeOffline.setGroupId(groupId);
        tradeOffline.setOrderId(orderNo);
        tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());
        tradeOffline.setPayerId(member.getId());
        tradeOffline.setPayerName(member.getName());
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        tradeOffline.setOrderAmount((Integer) rechargeInfo.get("actualAmount"));
        tradeOffline.setRealAmount(payAmount);
        tradeOffline.setReceiverType((byte) CommonEnum.UserType.User.getType());
        tradeOffline.setReceiverId(member.getId()+"");
        tradeOffline.setReceiverName(member.getName());
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Recharge.getType());       
        tradeOffline.setGmtCreate(date);
        tradeOffline.setGmtModified(date);
        tradeOffline.setMemo("实体卡线下充值");
        int i = tradeOfflineMapper.insertSelective(tradeOffline);

        if(i == 1) {
            rechargeInfo.put("responseCode", 1);
        } else {
            rechargeInfo.put("responseCode", -1);
            rechargeInfo.put("responseMsg", "服务器处理错误");
        }

        return rechargeInfo;
    }

    /*
    * 充值交易流水上传
    * */
    public Map<String,Object> saveRechargeTradeUpload(Map<String, Object> params) {
        Integer sid = (Integer) params.get("sid");
        Integer payAmount = (Integer) params.get("payAmount");
        String orderNo = (String) params.get("orderNo");

        if(sid == null || payAmount == null || Tools.isEmpty(orderNo)) {
            return null;
        }

        String activateCode = (String) params.get("activateCode");  //终端号
        String merchantNo = (String) params.get("merchantNo");      //商户号
        String transNo = (String) params.get("transNo");
        String authCode = (String) params.get("authCode");
        String serialNum = (String) params.get("serialNum");        //终端序列号
        Integer payType = (Integer) params.get("payType");          //支付方式
        String operator_num = (String) params.get("operator_num");  //操作员号

        if(Tools.isEmpty(activateCode) || Tools.isEmpty(merchantNo) || Tools.isEmpty(serialNum) || payType == null) {
            return null;
        }

        Map<String, Object> rechargeTradeUploadInfo = new HashMap<>();
        Date date = new Date();

        Long shopId = (long) sid;

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");
        String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();

        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(orderNo);
        if(tradeOffline == null) {
            return null;
        }

        Member member = memberMapper.selectByPrimaryKey(tradeOffline.getPayerId());
        MemberICCardInfo memberICCardInfo = memberICCardInfoMapper.getBoundICCardByMemberId(tradeOffline.getPayerId());

        tradeOffline.setTermSerial(serialNum);
        tradeOffline.setMerchantNo(merchantNo);
        tradeOffline.setTransNo(transNo);
        tradeOffline.setTransOrderNo(authCode);
        tradeOffline.setPayType((byte)(int)payType);
        if(payType.intValue()==BizEnum.PaymentType.Cash.getType()||payType.intValue()==BizEnum.PaymentType.BankCard.getType()){
        	 tradeOffline.setSubType((byte)BizEnum.PaymentScene.POS.getType());
        }else if(payType.intValue()==BizEnum.PaymentType.WebChat.getType()||payType.intValue()==BizEnum.PaymentType.AliPay.getType()){
       	 tradeOffline.setSubType((byte)BizEnum.PaymentScene.Scan.getType());
       }
//        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        
        tradeOffline.setTransactionStatus((byte) BizEnum.OfflineRechargeTransStatus.Success.getType());
        tradeOffline.setGmtModified(date);
        String  packageOrderNo=UtilFun.createOrderNum();
        tradeOffline.setPayOrderid(packageOrderNo);
        try {

            String iswithdraw = "0";
            //判断充值金额和实得金额是否相同来判断是否有活动
            if(tradeOffline.getRealAmount().equals(tradeOffline.getOrderAmount())) {//相同则没有活动
                iswithdraw = "1";
            }

            walletService.updateUserLockedAmount(member.getVirtualCard(), payGroupCode, member.getUserId(), tradeOffline.getRealAmount()+"", iswithdraw, 0,tradeOffline.getOrderId());

            Integer amt=tradeOffline.getOrderAmount() - tradeOffline.getRealAmount();
            if(amt>0){ 
            	
            	 walletService.updateUserLockedAmount(member.getVirtualCard(), payGroupCode, member.getUserId(), amt+"", iswithdraw, 0,tradeOffline.getOrderId());
            }

            //进行充值分润计算
            Group group = groupMapper.selectInfo(tradeOffline.getGroupId());
            if(group.getIsRechange() == 1) {
                profitStatisService.oneOrderProfitCalculate(tradeOffline, tradeOffline.getRealAmount());
            }
            
            tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);

            
            Wallet wallet=walletService.selectwallet(member.getVirtualCard(), payGroupCode, member.getUserId());
            
            if(wallet!=null) {
                rechargeTradeUploadInfo.put("pacektRemian", wallet.getCanBalance());
                rechargeTradeUploadInfo.put("realize_card_num", "");
                rechargeTradeUploadInfo.put("member_name", member.getName());
            } else {
                rechargeTradeUploadInfo.put("responseCode", 1);
                rechargeTradeUploadInfo.put("responseMsg", "余额查询失败");
                return rechargeTradeUploadInfo;
            }
            
        } catch (Exception e) {
            rechargeTradeUploadInfo.put("responseCode", -1);
            rechargeTradeUploadInfo.put("responseMsg", "服务器处理错误");
            return rechargeTradeUploadInfo;
        }

        rechargeTradeUploadInfo.put("responseCode", 1);
        rechargeTradeUploadInfo.put("actualAmount", tradeOffline.getOrderAmount());
        return rechargeTradeUploadInfo;
    }


    
    
    //支付密码修改
    public Map<String,Object> saveChangePassword(Map<String, Object> params) throws Exception {
        String icCardNo = (String) params.get("icCardNo");
        String oldPassword = (String) params.get("oldPassword");
        String newPassword = (String) params.get("newPassword");

        if(Tools.isEmpty(icCardNo) || Tools.isEmpty(oldPassword) || Tools.isEmpty(newPassword)) {
            return null;
        }

        Map<String, Object> changePasswordInfo = new HashMap<>();

        Member member = memberICCardInfoMapper.getMemberByICCardNo(icCardNo);
        if(member == null) {
            changePasswordInfo.put("responseCode", -1);
            changePasswordInfo.put("responseMsg", "卡还未绑定用户信息");
            return changePasswordInfo;
        }

        oldPassword = AES.AESEncode(Const.AceKey, oldPassword);
        newPassword = AES.AESEncode(Const.AceKey, newPassword);

        int i = memberMapper.changeTradePasswordByICCardNo(icCardNo, oldPassword, newPassword);
        if(i != 1) {
            changePasswordInfo.put("responseCode", -1);
            changePasswordInfo.put("responseMsg", "原支付密码错误");
        } else {
            Group group = groupMapper.selectByPrimaryKey(member.getGroupId());
            PayUpdatePayPwd payUpdatePayPwd = PayUpdatePayPwd.initialize(member.getVirtualCard(), oldPassword,newPassword, group.getPayGroupCode(),
                    UtilFun.createRandomNum(10), DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createOrderNum());
            PayResult payResult = IPayAPI.updateAccountPayPwd(payUpdatePayPwd);
            if(!payResult.getRespCode().equals("0000")) {
                throw new Exception("操作失败");
            }
            changePasswordInfo.put("responseCode", 1);
        }

        return changePasswordInfo;
    }

    //商品券识别
    public Map<String, Object> couponInfo(Map<String, Object> params) {
        Integer sid = (Integer) params.get("sid");
        String couponCode = (String) params.get("couponCode");
        String terminalSerial = (String) params.get("terminalSerial");

        if(sid == null || Tools.isEmpty(couponCode)) {
            return null;
        }

        Long shopId = (long) sid;
        Map<String, Object> couponInfo = new HashMap<>();


        //对门票的处理 订单号 包含TICK的不按门店走
        OrderServiceGoodDetail orderServiceGoodDetail = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNo(couponCode);

        if(orderServiceGoodDetail==null){
            couponInfo.put("responseCode", -1);
            couponInfo.put("responseMsg", "券码未识别");
            return couponInfo;
        }
        if(orderServiceGoodDetail.getOrderNo().contains("TICK")){
            couponInfo =  orderServiceGoodDetailMapper.getCouponInfo(null, couponCode);
            if(couponInfo != null) {
                Integer a = Integer.parseInt(couponInfo.get("oldAmount").toString() == null ? "0" : couponInfo.get("oldAmount").toString());
                Integer b = Integer.parseInt(couponInfo.get("payAmount").toString() == null ? "0" : couponInfo.get("payAmount").toString());
                couponInfo.put("payAmount", a);
                couponInfo.put("oldAmount", b);
                couponInfo.put("isCorrect",couponInfo.get("isCorrect"));
                ActivityEnum.CouponCodeStatus[] couponCodeStatuses = ActivityEnum.CouponCodeStatus.values();
                for (int i = 0; i < couponCodeStatuses.length; i++) {
                    if (couponCodeStatuses[i].getType() == (Integer) couponInfo.get("status")) {
                        couponInfo.put("statusName", couponCodeStatuses[i].getName());
                        break;
                    }
                }
            }
        }else{

            couponInfo =  orderServiceGoodDetailMapper.getCouponInfo(shopId + "", couponCode);
            if(couponInfo != null) {
                ActivityEnum.CouponCodeStatus[] couponCodeStatuses = ActivityEnum.CouponCodeStatus.values();
                Integer  a = Integer.parseInt(couponInfo.get("oldAmount").toString()==null ? "0" :couponInfo.get("oldAmount").toString());
                Integer  b = Integer.parseInt(couponInfo.get("payAmount").toString()==null ? "0" :couponInfo.get("payAmount").toString());
                couponInfo.put("payAmount", a);
                couponInfo.put("oldAmount", b);
                couponInfo.put("isCorrect",couponInfo.get("isCorrect"));
                for(int i = 0; i < couponCodeStatuses.length; i++) {
                    if(couponCodeStatuses[i].getType() == (Integer)couponInfo.get("status")) {
                        couponInfo.put("statusName", couponCodeStatuses[i].getName());
                        break;
                    }
                }
            } else {
                couponInfo = new HashMap<>();
                couponInfo.put("responseCode", -1);
                couponInfo.put("responseMsg", "券码未识别");
                return couponInfo;
            }
        }

        couponInfo.put("responseCode", 1);
        return couponInfo;
    }

    //券码核销
    public Map<String,Object> couponVerify(Map<String, Object> params,String rootHomeUrl) throws ParseException {
        Integer sid = (Integer) params.get("sid");
        String couponCode = (String) params.get("couponCode");
        String orderNo = (String) params.get("orderNo");
        String terminalSerial = (String) params.get("terminalSerial");

        Date date = new Date();

        if(sid == null || Tools.isEmpty(couponCode) || Tools.isEmpty(terminalSerial) || Tools.isEmpty(orderNo)) {
            return null;
        }

        Long shopId = (long) sid;
        System.out.print(shopId);

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");


        String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();

        Map<String, Object> posInfo = devicePosMapper.selectByTerminalSn(terminalSerial);
        if(posInfo == null) {
            return null;
        }

        Map<String, Object> couponVerifyInfo = new HashMap<>();


        //门票逻辑
        OrderServiceGoodDetail orderServiceGoodDetail =new OrderServiceGoodDetail();
//        orderServiceGoodDetail = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNo(couponCode);
        orderServiceGoodDetail = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNoData(couponCode,(Long) shopInfo.get("groupId"));
        if(orderServiceGoodDetail ==null){
            couponVerifyInfo.put("responseCode", -1);
            couponVerifyInfo.put("responseMsg", "订单号不存在");
        }

        if(orderServiceGoodDetail.getOrderNo().contains("TICK")){

        }else {
             orderServiceGoodDetail = orderServiceGoodDetailMapper.selectByCouponCode(couponCode, groupId, shopId);
            if (orderServiceGoodDetail == null) {
                couponVerifyInfo.put("responseCode", -1);
                couponVerifyInfo.put("responseMsg", "券码已失效(已被核销过)");
                return couponVerifyInfo;
            }
        }
        if(orderServiceGoodDetail.getOrderNo().contains("TICK")){


        }else{
            //门票的不走这段逻辑
            String[] shopIds = orderServiceGoodDetail.getCanUsedShop().split(",");

            for(int i = 0; i < shopIds.length; i++) {
                if(Long.parseLong(shopIds[i]) == sid) {
                    break;
                }

                if(i == shopIds.length - 1) {
                    couponVerifyInfo.put("responseCode", -1);
                    couponVerifyInfo.put("responseMsg", "当前门店不可核销");
                    return couponVerifyInfo;
                }
            }

            String beginTime = DateUtil.fomatDate(new Date(), DateUtil.sdfDay);
            String  endTime = DateUtil.fomatDate(orderServiceGoodDetail.getValidDate(), DateUtil.sdfDay);
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Date bt = sdf.parse(beginTime);
            Date et=sdf.parse(endTime);
            if(et.before(bt)) {
                couponVerifyInfo.put("responseCode", -1);
                couponVerifyInfo.put("responseMsg", "已过了可核销时间");
                return couponVerifyInfo;
            }
//            if(orderServiceGoodDetail.getValidDate().before(date)) {
//                couponVerifyInfo.put("responseCode", -1);
//                couponVerifyInfo.put("responseMsg", "已过了可核销时间");
//                return couponVerifyInfo;
//            }
        }


        OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(orderServiceGoodDetail.getOrderId());
        short usedNumber = orderServiceGood.getUsedNumber() == null ? 0 : orderServiceGood.getUsedNumber();
       //门票逻辑
        if(orderServiceGoodDetail.getOrderNo().contains("TICK")){
            orderServiceGood.setAllVerifyTime(date);
            orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.OrderFinished.getType());
            orderServiceGood.setUsedNumber(orderServiceGood.getNumber());
        }else{
            if(Integer.valueOf(usedNumber + 1).shortValue()== orderServiceGood.getNumber()) {
                orderServiceGood.setAllVerifyTime(date);
                orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForComment.getType());
//                orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.Verified.getType());
                orderServiceGood.setUsedNumber(orderServiceGood.getNumber());
            }else{
                orderServiceGood.setUsedNumber(Integer.valueOf(usedNumber + 1).shortValue());
            }
        }


   //     MallGood mallGood = mallGoodMapper.selectByPrimaryKey(orderServiceGood.getGoodId());

        //券码详情记录更新
        orderServiceGoodDetail.setCouponStatus(ActivityEnum.CouponCodeStatus.Verified.getType());
        orderServiceGoodDetail.setVerifyTime(date);
        orderServiceGoodDetail.setShopId(shopId);
        orderServiceGoodDetail.setPosId((Long) posInfo.get("deviceId"));
        orderServiceGoodDetail.setPosName((String) posInfo.get("posName"));
        orderServiceGoodDetail.setGmtModified(date);

        PayBalanceChange payBalanceChange = null;
        TradeOffline tradeOffline = null;
//        if(mallGood.getWalletSettleMode() == 0) { //如果结算位置是门店
//            logger.debug(">>>>>>>>结算位置门店，进行打款计算");
//            Integer settingPrice = new BigDecimal(orderServiceGoodDetail.getOriginalPrice()).multiply(new BigDecimal(mallGood.getSettlementRate()))
//                    .divide(new BigDecimal(10000), 2,BigDecimal.ROUND_FLOOR).intValue();
//            orderServiceGoodDetail.setSettingPrice(settingPrice);
//
//            //支付平台请求对象创建
//            payBalanceChange = PayBalanceChange.initialize(payGroupCode, (String) shopInfo.get("payMerchantCode"), orderServiceGoodDetail.getSettingPrice().toString(),
//                    "1", UtilFun.createOrderNum(), DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createRandomNum(10), "156");
//
//            Member member = memberMapper.selectByPrimaryKey(orderServiceGoodDetail.getMemberId());
//
//            //交易记录创建
//            tradeOffline = new TradeOffline();
//            tradeOffline.setGmtCreate(new Date());
//            tradeOffline.setGroupId(orderServiceGood.getGroupId());
//            tradeOffline.setOrderId(orderNo);
//            tradeOffline.setPayerId(member.getId());
//            tradeOffline.setPayerName(member.getName());
//            tradeOffline.setPayType((byte) CommonEnum.UserType.User.getType());
//            tradeOffline.setReceiverId(orderServiceGoodDetail.getShopId().toString());
//            tradeOffline.setReceiverName((String) shopInfo.get("shopName"));
//            tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
//            tradeOffline.setTransactionType((byte) BizEnum.TransactionType.CouponVerify.getType());
//            tradeOffline.setOrderAmount(orderServiceGoodDetail.getSettingPrice());
//            tradeOffline.setRealAmount(orderServiceGoodDetail.getSettingPrice());
//            tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
//            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
//            tradeOffline.setTransOrderNo(payBalanceChange.getOrgOrderNum());
//            tradeOffline.setMemo("券码核销打款到商户");
//        }
        try {
            posApiServiceTransactional.saveDoCouponVerify(orderServiceGood, orderServiceGoodDetail, payBalanceChange, tradeOffline);
            
            try {
            	templateMailSendService.sendCouponVerifyTemplate(shopId, orderServiceGood.getMemberId(), couponCode, orderServiceGood.getGoodName(), 
            			BizEnum.WebTemplateType.template8.getType(),orderServiceGood.getOrderNo(),rootHomeUrl);
			} catch (Exception e) {
				logger.info ("模板消息发送失败"+e); 
			  }
            
        } catch (Exception e) {
            e.printStackTrace();
            couponVerifyInfo.put("responseCode", -1);
            couponVerifyInfo.put("responseMsg", "服务器处理错误");
            return couponVerifyInfo;
        }
        couponVerifyInfo.put("responseCode", 1);
        return couponVerifyInfo;
    }

    //券码冲正
    public Map<String, Object> couponRefund(Map<String, Object> params) {
        Long sid = SysUtils.Object2Long(params.get("sid"));
        String couponCode = (String) params.get("couponCode");

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(sid);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Date dateAllowRefundTime = DateUtil.getAfterMinute(new Date(), -30);

        if(Tools.isEmpty(couponCode)) {
            return null;
        }
        Map<String, Object> couponRefundInfo = new HashMap<>();

        //门票逻辑
        OrderServiceGoodDetail  orderServiceGoodDetail2 = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNoData(couponCode,(Long) shopInfo.get("groupId"));
        if(orderServiceGoodDetail2==null){
            couponRefundInfo.put("responseCode", -1);
            couponRefundInfo.put("responseMsg", "订单号不存在");
        }
        //判断该券时候核销  未核销 不去冲正
        if(orderServiceGoodDetail2.getCouponStatus() ==2){
            int i = 0;
            if (orderServiceGoodDetail2.getOrderNo().contains("TICK")) {
                i = orderServiceGoodDetailMapper.updateRefundCoupon(null, couponCode, dateAllowRefundTime);
            } else {
                i = orderServiceGoodDetailMapper.updateRefundCoupon(sid, couponCode, dateAllowRefundTime);
            }
            if (i == 1) {
                //门票逻辑
                OrderServiceGoodDetail orderServiceGoodDetail = new OrderServiceGoodDetail();
                orderServiceGoodDetail = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNoData(couponCode,(Long) shopInfo.get("groupId"));
                if (orderServiceGoodDetail.getOrderNo().contains("TICK")) {//门票逻辑
                    orderServiceGoodDetail = orderServiceGoodDetailMapper.selectByCouponCode(couponCode, (Long) shopInfo.get("groupId"), null);

                    OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(orderServiceGoodDetail.getOrderId());
                    orderServiceGood.setUsedNumber((short)0);
                    orderServiceGood.setAllVerifyTime(null);
                    orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForUse.getType());
                    orderServiceGoodMapper.updateByPrimaryKeySelective(orderServiceGood);
                } else {
                    //正常逻辑
                    orderServiceGoodDetail = orderServiceGoodDetailMapper.selectByCouponCode(couponCode, (Long) shopInfo.get("groupId"), (Long) shopInfo.get("shopId"));
                    if(orderServiceGoodDetail==null){
                        couponRefundInfo.put("responseCode", -1);
                        couponRefundInfo.put("responseMsg", "订单号不存在");
                    }
                    OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(orderServiceGoodDetail.getOrderId());
                    orderServiceGood.setUsedNumber((short) (orderServiceGood.getUsedNumber() - 1));
                    orderServiceGood.setAllVerifyTime(null);
                    orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForUse.getType());
                    orderServiceGoodMapper.updateByPrimaryKeySelective(orderServiceGood);
                }
                couponRefundInfo.put("responseCode", 1);
            } else {
                couponRefundInfo.put("responseCode", -1);
                couponRefundInfo.put("responseMsg", "已超过可冲正时间或者券码已经冲正过一次");
            }
        }else {
            couponRefundInfo.put("responseCode", -1);
            couponRefundInfo.put("responseMsg", "该券码未核销,请先去核销");
        }
        return couponRefundInfo;
    }

    //异业优惠券识别
    public Map<String, Object> otherCouponInfo(Map<String, Object> params) {
        Long sid = SysUtils.Object2Long(params.get("sid"));
        String couponCode = (String) params.get("couponCode");
        String terminalSerial = (String) params.get("terminalSerial");

        if(Tools.isEmpty(couponCode)) {
            return null;
        }

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(sid);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }
        Long groupId = (Long) shopInfo.get("groupId");
        Map<String, Object>   otherCouponInfo = couponMapper.selectCouponByGroupIdAndCouponCode(groupId, couponCode, sid);
        if(otherCouponInfo == null) {
            otherCouponInfo = new HashMap<>();
            otherCouponInfo.put("responseCode", -1);
            otherCouponInfo.put("responseMsg", "优惠券未识别");
        } else {
        	//判断优惠券是否已经过期
        	Object startDate=otherCouponInfo.get("startTime");
        	Object endTime=otherCouponInfo.get("endTime");
        	System.out.println(startDate.getClass());
        	System.out.println(startDate+"---"+endTime+"...");
//        	String today=SysUtils.formatDate("yyyy-MM-dd HH:mm:ss");
//        	if(StringUtils.isNotBlank(startDate)){
//        		if(today.compareTo(startDate)<0){
//        			 otherCouponInfo.put("responseCode", -1);
//        	         otherCouponInfo.put("responseMsg", "优惠券未到使用时间");
//        	         return otherCouponInfo;
//        		}
//        	}
//        	
//        	if(StringUtils.isNotBlank(endTime)){
//        		if(endTime.compareTo(today)<0){
//        			 otherCouponInfo.put("responseCode", -1);
//        	         otherCouponInfo.put("responseMsg", "优惠券已过期");
//        	         return otherCouponInfo;
//        		}
//        	}
        	//
            otherCouponInfo.put("responseCode", 1);
        }
        return otherCouponInfo;
    }

    //异业优惠券锁定
    public Map<String, Object> otherCouponLock(Map<String, Object> params) {
        Long sid = SysUtils.Object2Long(params.get("sid"));
        String couponCode = (String) params.get("couponCode");
        String orderNo = (String) params.get("orderNo");
        Integer orderAmount = (Integer) params.get("orderAmount");

        if(Tools.isEmpty(couponCode) || Tools.isEmpty(orderNo) || orderAmount == null) {
            return null;
        }

        Date date = new Date();

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(sid);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }
        Long groupId = (Long) shopInfo.get("groupId");

        Map<String, Object> otherCouponLock = new HashMap<>();

        Map<String, Object> otherCouponInfo = couponMapper.selectCouponByGroupIdAndCouponCode(groupId, couponCode, sid);
        if(otherCouponInfo == null) {
            otherCouponLock.put("responseCode", -1);
            otherCouponLock.put("responseMsg", "优惠券未识别");
            return otherCouponLock;
        }

        int couponValue = (Integer)otherCouponInfo.get("value");
        int payAmount = orderAmount - couponValue;
        payAmount = payAmount < 0 ? 0 : payAmount;
        otherCouponLock.put("tradeMoney", orderAmount);
        otherCouponLock.put("couponCoverMoney", couponValue);
        otherCouponLock.put("realMoney", payAmount);

        TradeOffline tradeOffline = new TradeOffline();
        tradeOffline.setGroupId(groupId);
        tradeOffline.setOrderId(orderNo);
        tradeOffline.setGmtCreate(date);
        tradeOffline.setGmtModified(date);
        tradeOffline.setReceiverId(sid.toString());
        tradeOffline.setReceiverName((String) shopInfo.get("shopName"));
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        tradeOffline.setOrderAmount(orderAmount);
        tradeOffline.setDiscountAmount(couponValue);
        tradeOffline.setRealAmount(payAmount);

        try {
            posApiServiceTransactional.saveLockOtherCoupon(tradeOffline, groupId, couponCode, sid, date, (Long) otherCouponInfo.get("id"));
        } catch (ApplicationException e) {
            e.printStackTrace();
            otherCouponLock.put("responseCode", -1);
            otherCouponLock.put("responseMsg", "服务器处理错误");
            return otherCouponLock;
        }

        otherCouponLock.put("responseCode", 1);
        return otherCouponLock;
    }

    //POS订单取消
    public Map<String,Object> orderCancel(Map<String, Object> params) {
        String orderNo = (String) params.get("orderNo");

        Map<String, Object> orderCancelInfo = new HashMap<>();

        if(Tools.isEmpty(orderNo)) {
            return null;
        }

        try {
            posApiServiceTransactional.saveDoOrderCancel(orderNo);
        } catch (ApplicationException e) {
            e.printStackTrace();
            orderCancelInfo.put("responseCode", -1);
        }

        orderCancelInfo.put("responseCode", 1);
        return orderCancelInfo;
    }


    public Map<String,Object> tranUpload(Map<String, Object> params) {
        Long sid = SysUtils.Object2Long(params.get("sid"));
        Long t = SysUtils.Object2Long(params.get("t"));
        if(sid == null || t == null) {
            return null;
        }
        String orderNo = (String) params.get("clientOrderNo");  //订单号
//        String termSerial = (String) params.get("serialNum");   //终端设备序列号
        Integer payType = 0;      //支付类型
        if(!Tools.isEmpty(params.get("payType")+"")){
            payType = Integer.valueOf(params.get("payType")+"");
        }
        String cardNo = (String) params.get("cardNo");          //会员卡号
        String activateCode = (String) params.get("activateCode");  //终端号 终端序列号（钱包）
        String merchantNo = (String) params.get("merchantNo");  //商户号 大商户号（钱包）
        String transNo = (String) params.get("transNo");        //交易流水号
        String couponSns = (String) params.get("couponSns");    //优惠券
        String authCode = (String) params.get("authCode");      //交易机构订单号
        String payCardNo = (String) params.get("payCardNo"); //支付卡号

        Integer payAmount=0;                               //支付金额


        Integer cash = 0;      //支付类型
        if(!Tools.isEmpty(params.get("cash")+"")){
            cash = Integer.valueOf(params.get("cash")+"");
        }
        if(cash == null || cash == 0) {

            if(!Tools.isEmpty(params.get("bankAmount")+"")){
                payAmount = Integer.valueOf(params.get("bankAmount")+"");
            }
        } else {
            payAmount = cash;
        }
//
//        if(payType == null || Tools.isEmpty(orderNo) || Tools.isEmpty(termSerial)) {
//            return null;
//        }
//
//        Map<String, Object> result1 = devicePosMapper.getScanOrganizationByPosTerminalSn(termSerial);
//        if(result1 == null) {
//            return null;
//        }

        Byte subType = 0;

        switch (payType) {
            case 6:
                subType = (byte) BizEnum.PaymentScene.POS.getType();
                break;
            case 1:
            case 3:
            case 4:
            case 5:
            case 13:
                subType = (byte)BizEnum.PaymentScene.Scan.getType();
                break;
        }

        Date date = new Date();
        //返回数据
        Map<String, Object> newBenefitInfo = new HashMap<>();
        Map shop = shopMapper.getShopInfoById(sid);
//        Map shop = shopMapper.getShopById(sid);

//        Device device = deviceMapper.selectByserialNum(termSerial);
//        if(device==null||!sid.equals(device.getShopId())){
//            newBenefitInfo.put("responseCode", -1);
//            newBenefitInfo.put("responseMsg", "POS不存在");
//            return newBenefitInfo;
//        }
//        Long groupId=device.getGroupId();
        Long groupId = Long.parseLong(shop.get("group_id").toString());

        //交易流水创建或修改
        TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(orderNo);

        Member member = null;
        if(!Tools.isEmpty(cardNo)) {
            //会员交易
            member = memberMapper.getMemberByCardNoOrPhone(sid, cardNo); //查询用户信息
            if(member != null) {
                groupId = member.getGroupId();
            } else {
                newBenefitInfo.put("responseCode", -1);
                newBenefitInfo.put("responseMsg", "请求非法");
                return newBenefitInfo;
            }
        }

        //判断使用的优惠券是否是异业优惠券

        if(StringUtils.isNotBlank(couponSns)){
            try {
                member =finishProcessOtherSns(couponSns,member);
            } catch (Exception e) {
                e.printStackTrace();
                newBenefitInfo.put("responseCode", -1);
                newBenefitInfo.put("responseMsg", "优惠券码不存在");
                return newBenefitInfo;
            }
        }


        if(member==null){
            //非会员交易
            logger.debug(">>>>>>非会员交易处理");
            if(tradeOffline == null) {
                tradeOffline = new TradeOffline();
            } else {
                //如果POS机端重新上传交易流水，并且本交易已经处理成功
                if(tradeOffline.getTransactionStatus()==(byte)BizEnum.TransactionStatus.Success.getType()) {
                    newBenefitInfo = getBenefitInfo(tradeOffline, transNo, newBenefitInfo);
                    newBenefitInfo.put("responseCode", 1);
                    return newBenefitInfo;
                }
            }

            tradeOffline.setGroupId(groupId);
            tradeOffline.setRealAmount(payAmount);
            tradeOffline.setOrderAmount(payAmount);
            tradeOffline.setDiscountAmount(0);
            tradeOffline.setOrderId(orderNo);
            tradeOffline.setPayType((byte)(int)payType);
            tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
            tradeOffline.setTermSerial(null);
            tradeOffline.setMerchantNo(merchantNo);
            tradeOffline.setTerminalNo(activateCode);
            tradeOffline.setTransNo(transNo);
            tradeOffline.setTransOrderNo(authCode);
            tradeOffline.setScanOrganization(null);
//            tradeOffline.setScanOrganization((byte)(int) result1.get("scanOrganization"));
            tradeOffline.setIsWallet(false);
            tradeOffline.setGmtCreate(date);
            tradeOffline.setGmtModified(date);
            tradeOffline.setReceiverName((String) shop.get("merchant_name"));
            tradeOffline.setReceiverId(sid.toString());
            tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
            tradeOffline.setSubType(subType);
            tradeOffline.setPayAccount(payCardNo);
            int i=0;
            if(tradeOffline.getId()!=null&&tradeOffline.getId()>0){
                i = tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
            }else{
                i = tradeOfflineMapper.insertSelective(tradeOffline);
            }

            if(StringUtils.isNotBlank(couponSns)){
                try {
                    posApiServiceTransactional.saveVerifyCouponAndUpdateTrade(tradeOffline, couponSns, sid);
                } catch (ApplicationException e) {
                    e.printStackTrace();
                    newBenefitInfo.put("responseCode", -1);
                    newBenefitInfo.put("responseMsg", "服务器处理错误");
                    return newBenefitInfo;
                }
            }
            if(i == 1) {
                newBenefitInfo = newBenefitCalc(sid, payAmount, groupId, null, orderNo, tradeOffline.getId());
                newBenefitInfo.put("responseCode", 1);
                newBenefitInfo.put("responseMsg", "处理成功");
            } else {
                newBenefitInfo.put("responseCode", -1);
                newBenefitInfo.put("responseMsg", "服务器处理错误");
            }
            return newBenefitInfo;
        }



        //会员交易继续处理(不使用优惠)
        if(tradeOffline == null) {
            tradeOffline = new TradeOffline();
            tradeOffline.setReceiverId(sid.toString());
            tradeOffline.setGroupId(member.getGroupId());
            tradeOffline.setGmtCreate(date);
            tradeOffline.setGmtModified(date);
            tradeOffline.setOrderId(orderNo);
//            tradeOffline.setBonusAmount(0);
//            tradeOffline.setBonusValue(0);
//            tradeOffline.setDiscountAmount(0);
            tradeOffline.setOrderAmount(payAmount);
            tradeOffline.setRealAmount(payAmount);
        } else {
            //如果POS机端重新上传交易流水，并且本交易已经处理成功
            if(tradeOffline.getTransactionStatus()==(byte)BizEnum.TransactionStatus.Success.getType()) {
                newBenefitInfo = getBenefitInfo(tradeOffline, transNo, newBenefitInfo);
                newBenefitInfo.put("responseCode", 1);
                return newBenefitInfo;
            }
        }
        tradeOffline.setPayType((byte)(int)payType);
        tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
        tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
        tradeOffline.setTermSerial(null);
        tradeOffline.setMerchantNo(merchantNo);
        tradeOffline.setTerminalNo(activateCode);
        tradeOffline.setTransNo(transNo);
        tradeOffline.setTransOrderNo(authCode);
        tradeOffline.setScanOrganization(null);
//        tradeOffline.setScanOrganization((byte)(int) result1.get("scanOrganization"));
        tradeOffline.setGmtModified(new Date());
        tradeOffline.setPayerId(member.getId());
        tradeOffline.setPayerName(member.getName());
        tradeOffline.setPayerType((byte)CommonEnum.UserType.User.getType());
        tradeOffline.setReceiverName((String) shop.get("merchant_name"));
        tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
        tradeOffline.setSubType(subType);
        tradeOffline.setPayAccount(payCardNo);


        if(payType == 13 || payType == 14) {
            tradeOffline.setIsWallet(true);
        } else {
            tradeOffline.setIsWallet(false);
        }

        try {
            posApiServiceTransactional.saveVerifyCouponAndUpdateTrade(tradeOffline, couponSns, sid);
        } catch (ApplicationException e) {
            e.printStackTrace();
            newBenefitInfo.put("responseCode", -1);
            newBenefitInfo.put("responseMsg", "服务器处理错误");
            return newBenefitInfo;
        }

        try {
            memberService.insertMemberTradeDataAsyn(member.getId(),tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //新建线程进行分润计算和会员消费数据计算
        new Thread(new AfterTransUploadThread(tradeOffline.getId(), profitStatisService)).start();


        //会员门店关系
        memberShopRelation(member.getId(), sid, date, payAmount);

        //计算新的会员权益
        newBenefitInfo = newBenefitCalc(sid, payAmount, groupId, member, orderNo, tradeOffline.getId());
        newBenefitInfo.put("responseCode", 1);
        return newBenefitInfo;
    }


    public Map<String, Object> appCouponRefund(Map<String, Object> params) {
        Long sid = SysUtils.Object2Long(params.get("sid"));
        String couponCode = (String) params.get("couponCode");

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(sid);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Date dateAllowRefundTime = DateUtil.getAfterMinute(new Date(), -30);

        if(Tools.isEmpty(couponCode)) {
            return null;
        }
        Map<String, Object> couponRefundInfo = new HashMap<>();

        //门票逻辑
        OrderServiceGoodDetail  orderServiceGoodDetail2 = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNoData(couponCode,(Long) shopInfo.get("groupId"));
        if(orderServiceGoodDetail2==null){
            couponRefundInfo.put("responseCode", -1);
            couponRefundInfo.put("responseMsg", "订单号不存在");
        }
        //判断该券时候核销  未核销 不去冲正
        if(orderServiceGoodDetail2.getCouponStatus() ==2){
            int i = 0;
            if (orderServiceGoodDetail2.getOrderNo().contains("TICK")) {
                i = orderServiceGoodDetailMapper.updateRefundCoupon(null, couponCode, dateAllowRefundTime);
            } else {
                i = orderServiceGoodDetailMapper.updateRefundCoupon(sid, couponCode, dateAllowRefundTime);
            }
            if (i == 1) {
                //门票逻辑
                OrderServiceGoodDetail orderServiceGoodDetail = new OrderServiceGoodDetail();

                //正常逻辑
                orderServiceGoodDetail = orderServiceGoodDetailMapper.selectByCouponCode(couponCode, (Long) shopInfo.get("groupId"), (Long) shopInfo.get("shopId"));
                if(orderServiceGoodDetail==null){
                    couponRefundInfo.put("responseCode", -1);
                    couponRefundInfo.put("responseMsg", "订单号不存在");
                }
                OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(orderServiceGoodDetail.getOrderId());
                orderServiceGood.setUsedNumber((short) (orderServiceGood.getUsedNumber() - 1));
                orderServiceGood.setAllVerifyTime(null);
                orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.WaitingForUse.getType());
                orderServiceGoodMapper.updateByPrimaryKeySelective(orderServiceGood);

                couponRefundInfo.put("responseCode", 1);
            } else {
                couponRefundInfo.put("responseCode", -1);
                couponRefundInfo.put("responseMsg", "已超过可冲正时间或者券码已经冲正过一次");
            }
        }else {
            couponRefundInfo.put("responseCode", -1);
            couponRefundInfo.put("responseMsg", "该券码未核销,请先去核销");
        }
        return couponRefundInfo;
    }

    public Map<String,Object> appCouponVerify(Map<String, Object> params) throws ParseException{

        Integer sid = (Integer) params.get("sid");
        String couponCode = (String) params.get("couponCode");
//        String orderNo = (String) params.get("orderNo");

        Date date = new Date();

        if(sid == null || Tools.isEmpty(couponCode)) {
            return null;
        }

        Long shopId = (long) sid;
        System.out.print(shopId);

        Map<String, Object> shopInfo = shopGroupRelationMapper.selectShopInfoByShopId(shopId);
        if(shopInfo == null || shopInfo.size() == 0) {
            return null;
        }

        Long groupId = (Long) shopInfo.get("groupId");


        String payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();


        Map<String, Object> couponVerifyInfo = new HashMap<>();


        //门票逻辑
        OrderServiceGoodDetail orderServiceGoodDetail =new OrderServiceGoodDetail();
        orderServiceGoodDetail = orderServiceGoodDetailMapper.queryOrderServiceGoodOrderNo(couponCode);
        if(orderServiceGoodDetail ==null){
            couponVerifyInfo.put("responseCode", -1);
            couponVerifyInfo.put("responseMsg", "订单号不存在");
        }


        orderServiceGoodDetail = orderServiceGoodDetailMapper.selectByCouponCode(couponCode, groupId, shopId);
        if (orderServiceGoodDetail == null) {
            couponVerifyInfo.put("responseCode", -1);
            couponVerifyInfo.put("responseMsg", "券码已失效(已被核销过)");
            return couponVerifyInfo;
        }


        String[] shopIds = orderServiceGoodDetail.getCanUsedShop().split(",");

        for(int i = 0; i < shopIds.length; i++) {
            if(Long.parseLong(shopIds[i]) == sid) {
                break;
            }

            if(i == shopIds.length - 1) {
                couponVerifyInfo.put("responseCode", -1);
                couponVerifyInfo.put("responseMsg", "当前门店不可核销");
                return couponVerifyInfo;
            }
        }

        String beginTime = DateUtil.fomatDate(new Date(), DateUtil.sdfDay);
        String  endTime = DateUtil.fomatDate(orderServiceGoodDetail.getValidDate(), DateUtil.sdfDay);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date bt = sdf.parse(beginTime);
        Date et=sdf.parse(endTime);
        if(et.before(bt)) {
            couponVerifyInfo.put("responseCode", -1);
            couponVerifyInfo.put("responseMsg", "已过了可核销时间");
            return couponVerifyInfo;
        }



        OrderServiceGood orderServiceGood = orderServiceGoodMapper.selectByPrimaryKey(orderServiceGoodDetail.getOrderId());
        short usedNumber = orderServiceGood.getUsedNumber() == null ? 0 : orderServiceGood.getUsedNumber();


        if( ++usedNumber == orderServiceGood.getNumber()) {
            orderServiceGood.setAllVerifyTime(date);
            orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.OrderFinished.getType());
//                orderServiceGood.setOrderStatus(BizEnum.ServiceOrderStatus.Verified.getType());
        }
        orderServiceGood.setUsedNumber(usedNumber);



        //     MallGood mallGood = mallGoodMapper.selectByPrimaryKey(orderServiceGood.getGoodId());

        //券码详情记录更新
        orderServiceGoodDetail.setCouponStatus(ActivityEnum.CouponCodeStatus.Verified.getType());
        orderServiceGoodDetail.setVerifyTime(date);
        orderServiceGoodDetail.setShopId(shopId);
//        orderServiceGoodDetail.setPosId((Long) posInfo.get("deviceId"));
//        orderServiceGoodDetail.setPosName((String) posInfo.get("posName"));
        orderServiceGoodDetail.setGmtModified(date);

        PayBalanceChange payBalanceChange = null;
        TradeOffline tradeOffline = null;
//        if(mallGood.getWalletSettleMode() == 0) { //如果结算位置是门店
//            logger.debug(">>>>>>>>结算位置门店，进行打款计算");
//            Integer settingPrice = new BigDecimal(orderServiceGoodDetail.getOriginalPrice()).multiply(new BigDecimal(mallGood.getSettlementRate()))
//                    .divide(new BigDecimal(10000), 2,BigDecimal.ROUND_FLOOR).intValue();
//            orderServiceGoodDetail.setSettingPrice(settingPrice);
//
//            //支付平台请求对象创建
//            payBalanceChange = PayBalanceChange.initialize(payGroupCode, (String) shopInfo.get("payMerchantCode"), orderServiceGoodDetail.getSettingPrice().toString(),
//                    "1", UtilFun.createOrderNum(), DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createRandomNum(10), "156");
//
//            Member member = memberMapper.selectByPrimaryKey(orderServiceGoodDetail.getMemberId());
//
//            //交易记录创建
//            tradeOffline = new TradeOffline();
//            tradeOffline.setGmtCreate(new Date());
//            tradeOffline.setGroupId(orderServiceGood.getGroupId());
//            tradeOffline.setOrderId(orderNo);
//            tradeOffline.setPayerId(member.getId());
//            tradeOffline.setPayerName(member.getName());
//            tradeOffline.setPayType((byte) CommonEnum.UserType.User.getType());
//            tradeOffline.setReceiverId(orderServiceGoodDetail.getShopId().toString());
//            tradeOffline.setReceiverName((String) shopInfo.get("shopName"));
//            tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
//            tradeOffline.setTransactionType((byte) BizEnum.TransactionType.CouponVerify.getType());
//            tradeOffline.setOrderAmount(orderServiceGoodDetail.getSettingPrice());
//            tradeOffline.setRealAmount(orderServiceGoodDetail.getSettingPrice());
//            tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
//            tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
//            tradeOffline.setTransOrderNo(payBalanceChange.getOrgOrderNum());
//            tradeOffline.setMemo("券码核销打款到商户");
//        }
        try {
            posApiServiceTransactional.saveDoCouponVerify(orderServiceGood, orderServiceGoodDetail, payBalanceChange, tradeOffline);

        } catch (Exception e) {
            e.printStackTrace();
            couponVerifyInfo.put("responseCode", -1);
            couponVerifyInfo.put("responseMsg", "服务器处理错误");
            return couponVerifyInfo;
        }
        couponVerifyInfo.put("responseCode", 1);
        return couponVerifyInfo;

    }

    /**
     *
     * @param member
     * @param orderAmount
     *            赠送金额
     * @param relatedTradeOfflineId
     * @param relatedActivityId
     * @return
     */
    public TradeOffline recordRecharge(Member member, Integer orderAmount, Long relatedTradeOfflineId, Long relatedActivityId, String OrgOrderNum) {
        TradeOffline recordRecharge = new TradeOffline();
        recordRecharge.setRelatedTradeOfflineId(relatedTradeOfflineId);// 关联交易记录ID
        recordRecharge.setRelatedActivityId(relatedActivityId);// 关联活动ID
        recordRecharge.setMemo("微信线上充值返现");
        recordRecharge.setDetail("微信线上充值返现");// 详情
        recordRecharge.setTransactionType((byte) BizEnum.TransactionType.RechargeBackCash.getType());
        recordRecharge.setGmtCreate(new Date());
        recordRecharge.setGmtModified(new Date());
        recordRecharge.setGroupId(member.getGroupId());
        recordRecharge.setOrderId(OrgOrderNum);
        recordRecharge.setPayerId(member.getId());// 会员id
        recordRecharge.setPayerName(member.getName());
        recordRecharge.setPayerType((byte) CommonEnum.UserType.User.getType());
        recordRecharge.setReceiverId(member.getId() + "");// 接收者id
        recordRecharge.setReceiverName(member.getName());// 接收者
        recordRecharge.setReceiverType((byte) CommonEnum.UserType.User.getType());
        recordRecharge.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
        recordRecharge.setOrderAmount(orderAmount);
        recordRecharge.setDiscountAmount(0);// 折扣金额
        recordRecharge.setRealAmount(orderAmount);// 实付金额
        recordRecharge.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
        recordRecharge.setTransactionStatus((byte) BizEnum.TransactionStatus.WaitingForPay.getType());
        recordRecharge.setIsWallet(true);
        recordRecharge.setTermSerial(null);
        recordRecharge.setMerchantNo(null);// 商户号
        recordRecharge.setTerminalNo(null);// 商户终端号
        recordRecharge.setTransNo(null); // 交易流水号
        recordRecharge.setTransOrderNo(null);// 交易机构订单号
        recordRecharge.setPayAccount("");// 支付卡号
        recordRecharge.setScanOrganization(null);// 扫码付入网机构
        recordRecharge.setCrcodeStr(null);
        recordRecharge.setOldOrderId(null);
        recordRecharge.setDividableAmount(0);// 可分润金额
        recordRecharge.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        recordRecharge.setPayOrderid(OrgOrderNum);
        recordRecharge.setPayBakOrderid(null);
        recordRecharge.setInNetCompany((byte) BizEnum.InNetCompany.fuqianla.getType());// 入网机构
        return recordRecharge;
    }


}
